zoukankan      html  css  js  c++  java
  • 设计模式-工厂模式

    一、工厂模式的原理

    编程中有很多设计模式,工厂模式就是一种。

      原理:只需要抽象的积累,不需要关心具体的实现层,实现了解耦操作(便于扩展与维护),通过多态,自动调用相对应的方法。

      缺点:新加一个类型,需要添加一批的代码

    优点: 1、一个调用者想创建一个对象,只要知道其名称就可以了。 2、扩展性高,如果想增加一个产品,只要扩展一个工厂类就可以。 3、屏蔽产品的具体实现,调用者只关心产品的接口。

    缺点:每次增加一个产品时,都需要增加一个具体类和对象实现工厂,使得系统中类的个数成倍增加,在一定程度上增加了系统的复杂度,同时也增加了系统具体类的依赖。这并不是什么好事。

    # 汽车类
    class Car:
        def info(self):
            print('Car父类')
    
    class Audi(Car):
        def info(self):
            print('Audi 汽车')
    
    class Tesla(Car):
        def info(self):
            print('Tesla 汽车')
    
    # 工厂类
    class Factory:
        def create(self):
            print('创建汽车,工厂基类')
    
    class AudiFactory(Factory):
        def create(self):
            print('创建Audi汽车')
            return Audi()
    
    class TeslaFactory(Factory):
        def create(self):
            print('创建Tesla汽车')
            return Tesla()
    
    
    audi = AudiFactory().create().info()
  • 相关阅读:
    poj2728 Desert King
    bzoj4289 Tax
    洛谷P4141消失之物
    Code Forces 698A Vacations
    Code Forces 543A Writing Code
    洛谷P1133 教主的花园
    poj3177 Redundant Paths
    bzoj1151 动物园
    bzoj1503 郁闷的出纳员
    bzoj1208 宠物收养所
  • 原文地址:https://www.cnblogs.com/louhui/p/8983058.html
Copyright © 2011-2022 走看看