理解:建立一个工厂类,并在工厂类中通过switch 语句来决定返回何种子类的实例
代码:
using System.Windows.Forms;
namespace DesignMode.FactoryMethod
{
//抽象商品类
public abstract class Goods
{
public abstract void Show();
}
//衣服
public class Clothes : Goods
{
public override void Show()
{
MessageBox.Show("衣服商品");
}
}
//鞋
public class Shoes : Goods
{
public override void Show()
{
MessageBox.Show("鞋商品");
}
}
//珠宝
public class Jewelry : Goods
{
public override void Show()
{
MessageBox.Show("珠宝商品");
}
}
public class SimplyFactory
{
public static Goods CreateGoods(string name)
{
Goods goods = null;
switch (name)
{
case "衣服":
goods = new Clothes();
break;
case "鞋":
goods = new Shoes();
break;
case "珠宝":
goods = new Jewelry();
break;
}
return goods;
}
}}
namespace DesignMode.FactoryMethod
{
//抽象商品类
public abstract class Goods
{
public abstract void Show();
}
//衣服
public class Clothes : Goods
{
public override void Show()
{
MessageBox.Show("衣服商品");
}
}
//鞋
public class Shoes : Goods
{
public override void Show()
{
MessageBox.Show("鞋商品");
}
}
//珠宝
public class Jewelry : Goods
{
public override void Show()
{
MessageBox.Show("珠宝商品");
}
}
public class SimplyFactory
{
public static Goods CreateGoods(string name)
{
Goods goods = null;
switch (name)
{
case "衣服":
goods = new Clothes();
break;
case "鞋":
goods = new Shoes();
break;
case "珠宝":
goods = new Jewelry();
break;
}
return goods;
}
}}
客户端代码:
private void btn_SimpleFactory_Click(object sender, EventArgs e)
{
Goods goods = SimplyFactory.CreateGoods("鞋");
goods.Show();
}