设计模式名称:从类级别获取类 [英] Name of Design Pattern: get class from class level
问题描述
framworktest.py:
class FrameWorkHttpClient(object):
....
class FrameWorkTestCase(unittest.TestCase):
#子类可以控制get_response()中使用的类
HttpClient = FrameWorkHttpClient
def get_response(self,url):
client = self.HttpClient()
返回client.get(url)
mytest.py:
class MyHttpClient(FrameWorkHttpClient):
....
class MyTestCase(FrameWorkTestCase):
HttpClient = MyHttpClient
def test_something(self):
response = self.get_response()
...
方法 get_response()
从 self
不是通过导入它。这样一个子类可以修改类并使用不同的 HttpClient
。
这个名字(get class来自课堂级别的设计模式?
这是一种反转控制还是依赖注入的方式?
您的代码与工厂方法模式非常相似。唯一的区别是您的变体使用工厂类变量而不是工厂方法。
Especially in unittests we use this "design pattern" I call "get class from class level"
framworktest.py:
class FrameWorkHttpClient(object):
....
class FrameWorkTestCase(unittest.TestCase):
# Subclass can control the class which gets used in get_response()
HttpClient=FrameWorkHttpClient
def get_response(self, url):
client=self.HttpClient()
return client.get(url)
mytest.py:
class MyHttpClient(FrameWorkHttpClient):
....
class MyTestCase(FrameWorkTestCase):
HttpClient=MyHttpClient
def test_something(self):
response=self.get_response()
...
The method get_response()
gets the class from self
not by importing it. This way a subclass can modify the class and use a different HttpClient
.
What's the name of this (get class from class level) "design pattern"?
Is this a way of "inversion of control" or "dependency injection"?
Your code is very similar to Factory method pattern. The only difference is that your variant uses factory class variable instead of factory method.
这篇关于设计模式名称:从类级别获取类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!