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.
更多推荐
设计模式名称:从类级别获取类
发布评论