三種模式
- 簡單工廠模式:簡單工廠模式是由一個工廠對象決定創(chuàng)建出哪一種產(chǎn)品類的實例。簡單工廠模式是工廠模式家族中最簡單實用的模式,可以理解為是不同工廠模式的一個特殊實現(xiàn)。

image.png
- Factory(工廠):核心部分,負(fù)責(zé)實現(xiàn)創(chuàng)建所有產(chǎn)品的內(nèi)部邏輯,工廠類可以被外界直接調(diào)用,創(chuàng)建所需對象
- Product(抽象類產(chǎn)品):工廠類所創(chuàng)建的所有對象的父類,封裝了產(chǎn)品對象的公共方法,所有的具體產(chǎn)品為其子類對象
- ConcreteProduct(具體產(chǎn)品):簡單工廠模式的創(chuàng)建目標(biāo),所有被創(chuàng)建的對象都是某個具體類的實例。它要實現(xiàn)抽象產(chǎn)品中聲明的抽象方法(有關(guān)抽象類)
實現(xiàn)
abstract class Product
{
public void MethName()
{
//公共方法的實現(xiàn)
}
public abstract void MethodDiff();
//聲明抽象業(yè)務(wù)方法
}
class ConcreteProductA : Product
{
public override void MethodDiff()
{
//業(yè)務(wù)方法的實現(xiàn)
}
}
class Factory
{
public static Product GetProduct(string arg)
{
Product product = null;
if(arg.Equals("A")
{
product = new ConcreteProductA();
//init
}
else if(arg.Equals("B"))
{
product = new ConcreteProductB();
//init
}
else
{
....//其他情況
}
return product;
}
}
class Program
{
static void Main(string[] args)
{
Product product;
product = Factory.GetProduct("A");//工廠類創(chuàng)建對象
Product.MethName();
product.MethodDiff();
}
}
- 工廠模式:抽象了工廠接口的具體產(chǎn)品,應(yīng)用程序的調(diào)用不同工廠創(chuàng)建不同產(chǎn)品對象。(抽象產(chǎn)品)
class MobileFactory:
""" 工廠模式 生產(chǎn)手機(jī)的工廠"""
def get_mobile(self):
pass
class HWFactory(MobileFactory):
def get_mobile(self):
return 'get a HW phone'
class IphoneFactory(MobileFactory):
def get_mobile(self):
return 'get an iphone'
hw, ip = HWFactory(), IphoneFactory()
print(hw.get_mobile()) # get a HW phone
print(ip.get_mobile()) # get an iphone
- 抽象工廠模式:在工廠模式的基礎(chǔ)上抽象了工廠,應(yīng)用程序調(diào)用抽象的工廠發(fā)發(fā)創(chuàng)建不同產(chǎn)品對象。(抽象產(chǎn)品+抽象工廠)
"""
抽象工廠模式
【假設(shè)】華為和蘋果都生產(chǎn)手機(jī)和屏幕,而我家只生產(chǎn)屏幕
"""
# 有屏幕和手機(jī)兩款產(chǎn)品
class Screen:
def __init__(self):
print('i am a screen')
class Mobile:
def __init__(self):
print('i am a mobile')
# 三個廠家各自的屏幕和手機(jī)
class HWScreen(Screen):
def __init__(self):
print('HW screen')
class IphoneScreen(Screen):
def __init__(self):
print('Iphone screen')
class MyScreen(Screen):
def __init__(self):
print('My screen')
class HWMobile(Mobile):
def __init__(self):
print('HW Mobile')
class IphoneMobile(Mobile):
def __init__(self):
print('Iphone Mobile')
# 生產(chǎn)工廠
class Factory:
def get_screen(self):
pass
def get_mobile(self):
pass
# 各家自己的工廠
class HWFactory(Factory):
def get_mobile(self):
return HWMobile()
def get_screen(self):
return HWScreen()
class IphoneFactory(Factory):
def get_screen(self):
return IphoneScreen()
def get_mobile(self):
return IphoneMobile()
class MyFactory(Factory):
def get_screen(self):
return MyScreen()
# 我要生產(chǎn)東西咯
hw, ip, my = HWFactory(), IphoneFactory(), MyFactory()
hw.get_mobile() # HW Mobile
hw.get_screen() # HW screen
ip.get_mobile() # Iphone Mobile
ip.get_screen() # Iphone screen
my.get_screen() # My screen