设计模式----抽象工厂模式----python

'''


            抽象工厂模式
定义一个工厂类接口,让工厂子类来创建一系列相关或相互依赖的对象。
例:生产一部手机,需要手机壳、CPU、操作系统三类对象进行组装,其中每类对象都有不同的种类。
对每个具体工厂,分别生产一部手机所需要的三个对象。
角色:

抽象工厂角色(Creator具体工厂角色(Concrete Creator抽象产品角色(Product具体产品角色(Concrete Product客户端(Client相比工厂方法模式,抽象工厂模式中的每个具体工厂都生产一套产品。
适用场景:

系统要独立于产品的创建与组合时
强调一系列相关的产品对象的设计以便进行联合使用时
提供一个产品类库,想隐藏产品的具体实现时
优点:

将客户端与类的具体实现相分离
每个工厂创建了一个完整的产品系列,使得易于交换产品系列
有利于产品的一致性(即产品之间的约束关系)


from abc import ABCMeta,abstractmethod

class Car(metaclass=ABCMeta):
    @abstractmethod
    def show_shape(self):
        pass
    @abstractmethod
    def show_engine(self):
        pass

class CarShape(metaclass=ABCMeta):
    @abstractmethod
    def show_shape(self):
        pass

class CarEngine(metaclass=ABCMeta):
    @abstractmethod
    def show_engine(self):
        pass

class Flowline(CarShape):
    def show_shape(self):
        print(" I am is flowline shape")
class NoFlowline(CarShape):
    def show_shape(self):
        print("I am is No flowline shape")
class OilEngine(CarEngine):
    def show_engine(self):
        print("I am is oil engine")

class SolarEnergy(CarEngine):
    def show_engine(self):
        print("I am is solar energy")

class BiYaDi(Car):
    def show_engine(self):
        return OilEngine()
    def show_shape(self):
        return Flowline()
class DaZhong(Car):
    def show_shape(self):
        return NoFlowline()
    def show_engine(self):
        return OilEngine()


class ClientCar(object):
    def __init__(self,shape,engine):
        self.shape=shape
        self.engine=engine

    def show_car(self):

        self.engine.show_engine()
        self.shape.show_shape()
def makeFactory(factory):
    shape=factory.show_shape()
    engine=factory.show_engine()
    return ClientCar(shape,engine)
# f=makeFactory(BiYaDi())
# p=f.show_car()
f=makeFactory(DaZhong())
p=f.show_car()
缺点: 难以支持新种类的(抽象)产品

猜你喜欢

转载自blog.csdn.net/weixin_42040854/article/details/80609739