设计模式(1)--工厂模式
程序员文章站
2024-01-21 14:40:28
...
概述:
在工厂模式中,我们创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
1.简单工厂模式:
from abc import ABCMeta, abstractmethod
#定义手机类的一个抽象方法,显示手机价格
#手机类的接口
class Phone(metaclass=ABCMeta):
@abstractmethod
def show_price(self, arg):
pass
class Applephone(Phone):
def show_price(self, arg):
print(f'苹果手机,{arg}元')
class Xiaomiphone(Phone):
def show_price(self, arg):
print(f'小米手机,{arg}元')
#手机工厂类,生产格品牌手机
class PhoneFactory:
def creat_phone(self, brand):
if brand == 'applephone':
return Applephone()
else :
return Xiaomiphone()
mkphone = PhoneFactory() #找到一家手机工厂
myphone = mkphone.creat_phone('applephone') #在该工厂生产一个手机
myphone.make_phone(200) #查看该手机价格
通俗解释:简单工厂就是将手机生产集合到一个大工厂,有不同需求的用户都在这个工厂里定制。
2.工厂方法模式:
from abc import ABCMeta, abstractmethod
#定义手机类的一个抽象方法,显示手机价格
#手机类的接口
class Phone(metaclass=ABCMeta):
@abstractmethod
def show_price(self, arg):
pass
class Applephone(Phone):
def show_price(self, arg):
print(f'苹果手机,{arg}元')
class Xiaomiphone(Phone):
def show_price(self, arg):
print(f'小米手机,{arg}元')
#工厂接口
class Factory(metaclass=ABCMeta):
@abstractmethod
def create_phone(self):
pass
#小米的工厂
class XiaomiFactory:
def create_phone(self):
return Xiaomiphone()
#苹果的工厂
class AppleFactory:
def create_phone(self):
return Applephone()
phone = XiaomiFactory() #找到小米的工厂
myphone=phone.create_phone() #在小米的工厂生产一部手机
myphone.show_price(400) #使用手机
通俗解释:工厂方法模式就是把简单工厂模式里的大工厂中的各个工厂独立,并统一各个工厂的接口。
3.抽象工厂模式:
from abc import ABCMeta, abstractmethod
#——————————————————————产品接口——————————————————————
class Cpu(metaclass=ABCMeta):
@abstractmethod
def show_cpu(self):
pass
class Screen(metaclass=ABCMeta):
@abstractmethod
def show_screen(self):
pass
#——————————————————————具体产品————————————————————————
class XiaomiCpu():
def show_cpu(self):
print('this is xiaomi cpu')
class AppleCpu():
def show_cpus(self):
print('this is apple cpu')
class Xiaomiscreen():
def show_screen(self):
print('this is xiaomi screen')
class Applescreen():
def show_screen(self):
print('this is apple screen')
#—————————————————————工厂接口——————————————————————
class Factory(metaclass=ABCMeta):
@abstractmethod
def make_cpu(self):
pass
@abstractmethod
def make_screen(self):
pass
#————————————————————具体工厂————————————————————————————
class XiaomiFactory(Factory):
def make_cpu(self):
return XiaomiCpu()
def make_screen(self):
return Xiaomiscreen()
class AppleFactory(Factory):
def make_cpu(self):
return AppleCpu()
def make_screen(self):
return Applescreen()
#————————————————客户端——————————————————————————
class Phone:
def __init__(self, cpu, screen):
self.cpu = cpu
self.screen = screen
def show_info(self):
self.cpu.show_cpu()
self.screen.show_screen()
def make_phone(factory):
cpu = factory.make_cpu()
screen = factory.make_screen()
return Phone(cpu, screen)
miphone = make_phone(XiaomiFactory())
miphone.show_info()
通俗解释:抽象工厂里集合了一个产品不同组件的实现