理解:为每种商品建立一个工厂,这样如果要加新的商品,就不用去改以前的工厂类代码.
代码:
using System.Collections.Generic;
using System.Text; using System.Windows.Forms;
namespace DesignMode.FactoryMethod { //抽象商品类 public abstract class Goods { public abstract void Show(); }
//抽象工厂类 public abstract class Goods_Factory { public abstract Goods CreateGoods(); }
//衣服 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 Clothes_Factory : Goods_Factory { public override Goods CreateGoods() { return new Clothes(); } }
public class Shoes_Factory : Goods_Factory { public override Goods CreateGoods() { return new Shoes(); } }
public class Jewelry_Factory : Goods_Factory { public override Goods CreateGoods() { return new Jewelry(); } } }
客户端代码:
private void btn_FactoryMethod_Click(object sender, EventArgs e)
{ Goods_Factory factory = new Shoes_Factory();// new Clothes_Factory(); Goods clothes = factory.CreateGoods(); clothes.Show(); }
|
请发表评论