设计模式名称:从类级别获取类

编程入门 行业动态 更新时间:2024-10-25 00:34:03
本文介绍了设计模式名称:从类级别获取类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 特别是在单元测试中,我们使用这种设计模式,我称之为从类级别获取类

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.

更多推荐

设计模式名称:从类级别获取类

本文发布于:2023-10-29 03:29:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538592.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:级别   名称   模式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!