Python设计模式 - 工厂模式

简单工厂模式

基于一个包含do_say()方法的Animal的抽象类创建两个类

  • Cat

  • Dog

from abc import ABCMeta, abstractmethod

class Animal(metaclass=ABCMeta):
    @abstractmethod
    def do_say(self):
        pass


class Dog(Animal):
    def do_say(self):
        print("Bhow Bhow!!")


class Cat(Animal):
    def do_say(self):
        print("Meow Meow!!")

创建一个包含make_sound()方法的工厂类ForestFactory

class ForestFactory(object):
    def make_sound(self, object_type):
        return eval(object_type)().do_say()

制造点声音

if __name__ == '__main__':
    ff = ForestFactory()
    animal = input("Which animal should make_sound?[Dog or Cat]")
    ff.make_sound(animal)
640?wx_fmt=jpeg
运行结果

类关系图

640?wx_fmt=jpeg
类关系图

工厂方法模式

有两个社交网站LinkedIn和Facebook,它们的个人简介界面有各自不同的内容

内容抽象类`Section`
from abc import ABCMeta, abstractmethod


class Section(metaclass=ABCMeta):
    @abstractmethod
    def describe(self):
        pass
不同的内容
  • PersonalSection

  • AlbumSection

  • PatenSection

  • PublicationSection

class PersonalSection(Section):
    def describe(self):
        print("Personal Section")


class AlbumSection(Section):
    def describe(self):
        print("Album Section")


class PatenSection(Section):
    def describe(self):
        print("Patent Section")


class PublicationSection(Section):
    def describe(self):
        print("Publication Section")
公司抽象类`Profile`
class Profile(metaclass=ABCMeta):
    def __init__(self):
        self.sections = []
        self.createProfile()

    @abstractmethod
    def createProfile(self):
        pass

    def getSections(self):
        return self.sections

    def addSections(self, section):
        self.sections.append(section)
公司类
  • linkedin

  • facebook

class linkedin(Profile):
    def createProfile(self):
        self.addSections(PersonalSection())
        self.addSections(PatenSection())
        self.addSections(PublicationSection())


class facebook(Profile):
    def createProfile(self):
        self.addSections(PersonalSection())
        self.addSections(AlbumSection())

选择一个社交网站

if __name__ == '__main__':
    profile_type = input("Which Profile you`d like to create?[LinkedIn or FaceBook]")
    profile = eval(profile_type.lower())()
    print("Creating Profile..", type(profile).__name__)
    print("Profile has sections --", profile.getSections())
640?wx_fmt=jpeg
测试结果

类关系图

640?wx_fmt=jpeg
工厂方法模式

抽象工厂模式

一家提供印式和美式披萨的店(抽象类PizzFactory

class PizzFactory(metaclass=ABCMeta):
    @abstractmethod
    def createVegPizza(self):
        pass

    @abstractmethod
    def createNonVegPizza(self):
        pass
  • IndianPizzaFactory

  • USPizzaFactory

class IndianPizzaFactory(PizzFactory):
    def createVegPizza(self):
        return DeluxVeggiePizza()

    def createNonVegPizza(self):
        return ChickenPizza()


class USPizzaFactory(PizzFactory):
    def createVegPizza(self):
        return MexicanVegPizza()

    def createNonVegPizza(self):
        return HamPizza()

两种不同的披萨(抽象类)

  • 素食披萨NonVegPizza

  • 非素食披萨VegPizza

class VegPizza(metaclass=ABCMeta):
    @abstractmethod
    def prepare(self):
        pass


class NonVegPizza(metaclass=ABCMeta):
    @abstractmethod
    def serve(self, VegPizza):
        pass

四种不同的披萨

  • DeluxVeggiePizza

  • ChickenPizza

  • MexicanVegPizza

  • HamPizza

class DeluxVeggiePizza(VegPizza):
    def prepare(self):
        print("Prepare ", type(self).__name__)


class ChickenPizza(NonVegPizza):
    def serve(self, VegPizza):
        print(type(self).__name__, " is served with Chicken on", type(VegPizza).__name__)


class MexicanVegPizza(VegPizza):
    def prepare(self):
        print("Prepare ", type(self).__name__)


class HamPizza(NonVegPizza):
    def serve(self, VegPizza):
        print(type(self).__name__, " is served with Ham on", type(VegPizza).__name__)

到此就完成了一家披萨店,有两个国家口味,各有荤素的披萨。

整合为一个制造披萨的工厂

class PizzaStore:
    def __init__(self):
        pass

    def makePizzas(self):
        for factory in [IndianPizzaFactory(), USPizzaFactory()]:
            self.factory = factory
            self.NonVegPizza = self.factory.createNonVegPizza()
            self.VegPizza = self.factory.createVegPizza()
            self.VegPizza.prepare()
            self.NonVegPizza.serve(self.VegPizza)

测试

if __name__ == '__main__':
    pizza = PizzaStore()
    pizza.makePizzas()
640?wx_fmt=jpeg
测试结果

类关系图

640?wx_fmt=jpeg
类关系图

工厂方法和抽象工厂方法

工厂方法抽象工厂方法
向客户端开发了一个创建对象的方法包含一个或多个工厂方法来创建一个系列的相关对象
使用继承和子类来决定要创建哪个对象使用组合将创建对象的任务委托给其他类
用于创建一个产品用于创建相关产品的系列

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值