《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();
}
}
}