简单工厂

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值