设计模式名称:从类级别获取类 [英] Name of Design Pattern: get class from class level

查看:137
本文介绍了设计模式名称:从类级别获取类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

特别是在单元测试中,我们使用这种设计模式,我称之为从类级别获取类



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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆