参考资料
《java与模式》
上面那本书上的例子举的是园丁和果园的例子,学习设计模式最好在生活中自己找个例子
实践一下,下面是我自己的一个例子,是讲快餐店的例子,快餐店提供很多食物,比如
面条,米饭,面包。首先定义了一个Food接口,然后这些食物都从它来继承,定义了一个大厨
他包办所有食物的制作工作,这就是我所理解的简单工厂模式的概念,下面是源代码:
using System;
namespace SimpleFactoryPattern
{
/// <summary>
/// 简单工厂模式示例
/// </summary>
class SimpleFactoryPattern
{
//定义Food接口
public interface Food
{
//烹饪
void Cook();
//卖出
void Sell();
}
//Noodle
public class Noodle:Food
{
public Noodle()
{
Console.WriteLine("\nThe Noodle is made..");
}
private int price;
//面条Noodle的Cook方法接口实现
public void Cook()
{
Console.WriteLine("\nNoodle is cooking...");
}
//面条Noodle的Sell方法接口实现
public void Sell()
{
Console.WriteLine("\nNoodle has been sold...");
}
public int Price
{
get{return this.price;}
set{price=value;}
}
}
//Rice
public class Rice:Food
{
public Rice()
{
Console.WriteLine("\nThe Rice is made ..");
}
private int price;
public void Cook()
{
Console.WriteLine("\nRice is cooking...");
}
public void Sell()
{
Console.WriteLine("\nRice has been sold...");
}
public int Price
{
get{return this.price;}
set{price=value;}
}
}
//Bread
public class Bread:Food
{
public Bread()
{
Console.WriteLine("\nThe Bread is made....");
}
private int price;
public void Cook()
{
Console.WriteLine("\nBread is cooking...");
}
public void Sell()
{
Console.WriteLine("\nBread has been sold...");
}
public int Price
{
get{return this.price;}
set{price=value;}
}
}
//定义大厨,他包办这个快餐店里的所有Food,包括面条,面包和米饭
class Chef
{
public static Food MakeFood(string foodName)
{
try
{
switch(foodName)
{
case "noodle": return new Noodle();
case "rice":return new Rice();
case "bread":return new Bread();
default:throw new BadFoodException("Bad food request!");
}
}
catch(BadFoodException e)
{
throw e;
}
}
}
//异常类,该餐馆没有的食品
class BadFoodException: System.Exception
{
public BadFoodException(string strMsg)
{
Console.WriteLine(strMsg);
}
}
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
Food food=Chef.MakeFood("bread");
food.Cook();
food.Sell();
Console.ReadLine();
}
}
}