首页 > 代码库 > 简单工厂模式(详细)(举例饮料)
简单工厂模式(详细)(举例饮料)
饮料案例:
饮料类(父类):
public class Drink
{
//虚方法
public virtual void Driking() {
}
}
可乐类(继承父类饮料类)
public class Cola:Drink
{
//重写父类的Driking()方法
public override void Driking()
{
Console.WriteLine("Cola");
}
}
雪碧类(继承父类饮料类)
public class Sprite:Drink
{
//重写父类的Driking()方法
public override void Driking()
{
Console.WriteLine("Sprite");
}
}
饮料工厂类(factory)
class DrinkFactory
{
public static Drink Init(string type) {
Drink drink = null;
switch(type){
case "可乐":
drink = new Cola();
break;
case "雪碧":
drink = new Sprite();
break;
}
return drink;
}
}
Main方法
class Program {
static void Main(string[] args) {
Console.WriteLine("请输入你要喝的饮料");
string type=Console.ReadLine();
Drink drink=DrinkFactory.Init(type);
drink.Driking();
Console.ReadKey();
}
}
简单工厂模式(详细)(举例饮料)