//////顾客充当客户端,负责调用简单工厂来生产对象///即客户点菜,厨师(相当于简单工厂)负责烧菜(生产的对象)///classCustomer
{staticvoidMain(string[] args)
{//客户想点一个西红柿炒蛋Food food1 = FoodSimpleFactory.CreateFood("西红柿炒蛋");
food1.Print();//客户想点一个土豆肉丝Food food2 = FoodSimpleFactory.CreateFood("土豆肉丝");
food2.Print();
Console.Read();
}
}//////菜抽象类///publicabstractclassFood
{//输出点了什么菜publicabstractvoidPrint();
}//////西红柿炒鸡蛋这道菜///publicclassTomatoScrambledEggs : Food
{publicoverridevoidPrint()
{
Console.WriteLine("一份西红柿炒蛋!");
}
}//////土豆肉丝这道菜///publicclassShreddedPorkWithPotatoes : Food
{publicoverridevoidPrint()
{
Console.WriteLine("一份土豆肉丝");
}
}//////简单工厂类, 负责 炒菜///publicclassFoodSimpleFactory
{publicstaticFood CreateFood(stringtype)
{
Food food=null;if(type.Equals("土豆肉丝"))
{
food=newShreddedPorkWithPotatoes();
}elseif(type.Equals("西红柿炒蛋"))
{
food=newTomatoScrambledEggs();
}returnfood;
}
}
.NET类库中是否有实现了简单工厂模式的类呢?
.NET中System.Text.Encoding类就实现了简单工厂模式,该类中的GetEncoding(int codepage)就是工厂方法
网友评论