工厂方法模式类似说段子中的我开了个餐厅,但是我的菜都是别的餐厅炒出来的,并不是我自己炒出来的,所以当我要吃西红柿炒鸡蛋的时候,这个餐厅就会找子餐厅去叫他炒
示例:
public class Food //菜品标准接口
{
public virtual double GetResult()
{
return "我不生产菜,我只是菜的搬运工";
}
}
class 西红柿炒鸡蛋 : Food
{
public virtual double GetResult()
{
return "给搬运工送西红柿炒鸡蛋";
}
}
class 青椒回锅肉 : Food
{
public virtual double GetResult()
{
return "给搬运工送青椒回锅肉";
}
}
class 茄子煲 : Food
{
public virtual double GetResult()
{
return "给搬运工送茄子煲";
}
}
public abstract class Factory
{
public abstract Operation CreateFood();
}
public class 西红柿炒鸡蛋餐厅 : Factory
{
public override Operation CreateFood()
{
return new 西红柿炒鸡蛋();
}
}
public class 青椒回锅肉餐厅 : Factory
{
public override Operation CreateFood()
{
return new 青椒回锅肉();
}
}
public class 茄子煲餐厅 : Factory
{
public override Operation CreateFood()
{
return new 茄子煲();
}
}
public class 客人{
static void Main(string[] args)
{
Factory fac = null;
switch ("西红柿炒鸡蛋")
{
case "西红柿炒鸡蛋":
fac = new 西红柿炒鸡蛋餐厅(); //返回产品
break;
case "青椒回锅肉":
fac = new 青椒回锅肉餐厅(); //返回产品
break;
case "茄子煲":
fac = new 茄子煲餐厅(); //返回产品
break;
}
}
}