会员
周边
众包
新闻
博问
闪存
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
xinerzhui 心儿醉
博客园
首页
新随笔
联系
订阅
管理
[设计模式]简单工厂模式(Simple Factory)
Code
using
System;
using
System.Collections.Generic;
using
System.Text;
namespace
Learning.DesignPattern
{
//
简单工厂模式(Simple Factory)
//
产品接口ICar
public
interface
ICar
{
void
Drive();
}
//
具体的产品类实现ICar接口
public
class
HongQi : ICar
{
public
void
Drive()
{
Console.WriteLine(
"
The driver driving the HongQi!
"
);
}
}
public
class
DaZhong : ICar
{
public
void
Drive()
{
Console.WriteLine(
"
The driver driving the DaZhong!
"
);
}
}
//
工厂类:
public
class
CarFactory
{
public
static
ICar DriveCar(
string
carName)
{
if
(carName
==
"
HongQi
"
)
{
return
new
HongQi();
}
else
if
(carName
==
"
DaZhong
"
)
{
return
new
DaZhong();
}
else
{
return
null
;
}
}
}
//
调用该工厂类,执行具体产品方法:
public
class
Program
{
public
static
void
Main()
{
string
carName
=
"
HongQi
"
;
Console.Write(
"
请输入车名:
"
);
Console.Write(
"
+>
"
);
carName
=
Console.ReadLine();
try
{
CarFactory.DriveCar(carName).Drive();
}
catch
{
Console.Write(
"
您输入的车名无效!
"
);
}
Console.ReadLine();
}
}
}
posted on
2008-10-14 20:25
心儿醉 xinerzhui
阅读(
159
) 评论(
0
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部