简体   繁体   English

Python 中的“鸭子打字”也是“立面设计模式”吗?

[英]Is 'duck typing' in Python also a 'Facade Design Pattern'?

Whenever we are able to call one function from different classes, would it be considered as Facade design pattern?每当我们能够从不同的类中调用一个 function 时,它会被视为外观设计模式吗?

class Mobile:
    def __init__(self, name, ram, memory):
        self.name = name
        self.ram = ram
        self.memory = memory
    
    def info(self):
        return self.name, self.ram, self.memory
    
class Printer:
    def __init__(self, name, size, color):
        self.name = name
        self.size= size
        self.color= color
    
    def info(self):
        return self.name, self.size, self.color
    
    
mob = Mobile("Dark", 8, 128)        
prt = Printer("Alpine", '4-5', 'white')   

print(mob.info())
print(prt.info())

In the above code we are using the same function for both the classes.在上面的代码中,我们对两个类使用相同的 function。 Would this be considered as a Facade design pattern?这会被视为外观设计模式吗?

A façade provides abstraction through a single interface外观通过单个接口提供抽象

You're not abstracting anything here, just defining two independent instance methods, which can be done in any OOP language, so duck typing is irrelevant你这里没有抽象任何东西,只是定义了两个独立的实例方法,可以用任何 OOP 语言完成,所以鸭子类型是无关紧要的

Note that your classes are the exact same, so you don't need two classes, only two instances of class Mobile请注意,您的课程完全相同,因此您不需要两个课程,只需class Mobile两个实例

class Mobile:
    def __init__(self, name, ram, memory):
        self.name = name
        self.ram = ram
        self.memory = memory
    
    def info(self):
        return self.name, self.ram, self.memory    
    
    
mob1 = Mobile("Dark", 8, 128)        
mob2 = Mobile("Alpine", 16, 128) 

If you defined an abstract base class , then you'd be using inheritance with subclasses, and still not a façade如果您定义了一个抽象基础 class ,那么您将使用 inheritance 和子类,但仍然不是外观

An example of a Façade in your case would be some operator routing a call/message (through a single interface) to any "mobile", where the mobiles could have completely different ways to contact them (which contact() could be defined as an abstract function in a parent class)在您的情况下,外观的一个示例是某些运营商将呼叫/消息(通过单个界面)路由到任何“移动设备”,其中移动设备可能具有完全不同的联系方式(其中contact()可以定义为父类中的抽象 function)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM