工廠模式

工廠模式

工廠模式

工廠模式

interface IFactory
{
Nightingale CreateNightingale();
}

class UndergraduateFactory : IFactory
{
public Nightingale CreateNightingale()
{
return new Undergraduate();
}
}

class VolunteerFactory : IFactory
{
public Nightingale CreateNightingale()
{
return new Volunteer();
}
}

IFactory factory = new UndergraduateFactory();
Nightingale student = new factory.CreateNightingale();

student.BuyRice();
student.Sweep();
student.Wash();

工廠模式克服了簡單工廠模式違背開放封閉原則的缺點,相較簡單
工廠模式進一步抽象和推廣,缺點是每加一個產品,就需要加一個
產品工廠的類別,增加了額外的開發量。