设计模式-简单工厂模式(SimpleFactory-C#)
2024-07-21 02:18:46
供稿:网友
《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();
}
}
}
本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。