第一章 简单工厂模式
/// <summary> /// 运算类 /// </summary> public class Operation { private double _numberA = 0; private double _numberB = 0; /// <summary> /// 数字A /// </summary> public double NumberA { get { return _numberA; } set { _numberA = value; } } /// <summary> /// 数字B /// </summary> public double NumberB { get { return _numberB; } set { _numberB = value; } } /// <summary> /// 得到运算结果 /// </summary> /// <returns></returns> public virtual double GetResult() { double result = 0; return result; } }
/// <summary> /// 加法类 /// </summary> class OperationAdd : Operation { public override double GetResult() { double result = 0; result = NumberA + NumberB; return result; } }
/// <summary> /// 运算类工厂 /// </summary> public class OperationFactory { public static Operation createOperate(string operate) { Operation oper = null; switch (operate) { case "+": { oper = new OperationAdd(); break; } case "-": { oper = new OperationSub(); break; } case "*": { oper = new OperationMul(); break; } case "/": { oper = new OperationDiv(); break; } case "sqr": { oper = new OperationSqr(); break; } case "sqrt": { oper = new OperationSqrt(); break; } case "+/-": { oper = new OperationReverse(); break; } } return oper; } }
第二章 策略模式
abstract class CashSuper { public abstract double acceptCash(double money); }
class CashRebate : CashSuper { private double moneyRebate = 1d; public CashRebate(string moneyRebate) { this.moneyRebate = double.Parse(moneyRebate); } public override double acceptCash(double money) { return money * moneyRebate; } }
//收费策略Context class CashContext { //声明一个现金收费父类对象 private CashSuper cs; //设置策略行为,参数为具体的现金收费子类(正常,打折或返利) public CashContext(CashSuper csuper) { this.cs = csuper; } //得到现金促销计算结果(利用了多态机制,不同的策略行为导致不同的结果) public double GetResult(double money) { return cs.acceptCash(money); } }
客户端:
private void btnOk_Click(object sender, EventArgs e) { CashContext cc = null; switch (cbxType.SelectedItem.ToString()) { case "正常收费": cc = new CashContext(new CashNormal()); break; case "满300返100": cc = new CashContext(new CashReturn("300", "100")); break; case "打8折": cc = new CashContext(new CashRebate("0.8")); break; } double totalPrices = 0d; totalPrices = cc.GetResult(Convert.ToDouble(txtPrice.Text) * Convert.ToDouble(txtNum.Text)); total = total + totalPrices; lbxList.Items.Add("单价:" + txtPrice.Text + " 数量:" + txtNum.Text + " " + cbxType.SelectedItem + " 合计:" + totalPrices.ToString()); lblResult.Text = total.ToString(); }
策略和简单工厂结合:
//现金收取工厂 class CashContext { CashSuper cs = null; //根据条件返回相应的对象 public CashContext(string type) { switch (type) { case "正常收费": CashNormal cs0 = new CashNormal(); cs = cs0; break; case "满300返100": CashReturn cr1 = new CashReturn("300", "100"); cs = cr1; break; case "打8折": CashRebate cr2 = new CashRebate("0.8"); cs = cr2; break; } } public double GetResult(double money) { return cs.acceptCash(money); } }
客户端代码:
//客户端窗体程序(主要部分) double total = 0.0d; private void btnOk_Click(object sender, EventArgs e) { //利用简单工厂模式根据下拉选择框,生成相应的对象 CashContext csuper = new CashContext(cbxType.SelectedItem.ToString()); double totalPrices = 0d; //通过多态,可以得到收取费用的结果 totalPrices = csuper.GetResult(Convert.ToDouble(txtPrice.Text) * Convert.ToDouble(txtNum.Text)); total = total + totalPrices; lbxList.Items.Add("单价:" + txtPrice.Text + " 数量:" + txtNum.Text + " " + cbxType.SelectedItem + " 合计:" + totalPrices.ToString()); lblResult.Text = total.ToString(); }
通过反射实现:
class CashContext { private CashSuper cs; public void setBehavior(CashSuper csuper) { this.cs = csuper; } public double GetResult(double money) { return cs.acceptCash(money); } }
xml:
<?xml version="1.0" encoding="utf-8" ?> <CashAcceptType> <type> <name>正常收费</name> <class>CashNormal</class> <para></para> </type> <type> <name>满300返100</name> <class>CashReturn</class> <para>300,100</para> </type> <type> <name>满200返50</name> <class>CashReturn</class> <para>200,50</para> </type> <type> <name>打8折</name> <class>CashRebate</class> <para>0.8</para> </type> <type> <name>打7折</name> <class>CashRebate</class> <para>0.7</para> </type> </CashAcceptType>
客户端:
private void btnOk_Click(object sender, EventArgs e) { CashContext cc = new CashContext(); //根据用户的选项,查询用户选择项的相关行 DataRow dr = ((DataRow[])ds.Tables[0].Select("name='" + cbxType.SelectedItem.ToString()+"'"))[0]; //声明一个参数的对象数组 object[] args =null; //若有参数,则将其分割成字符串数组,用于实例化时所用的参数 if (dr["para"].ToString() != "") args = dr["para"].ToString().Split(','); //通过反射实例化出相应的算法对象 cc.setBehavior((CashSuper)Assembly.Load("商场管理软件").CreateInstance("商场管理软件." + dr["class"].ToString(), false, BindingFlags.Default, null, args, null, null)); double totalPrices = 0d; totalPrices = cc.GetResult(Convert.ToDouble(txtPrice.Text) * Convert.ToDouble(txtNum.Text)); total = total + totalPrices; lbxList.Items.Add("单价:" + txtPrice.Text + " 数量:" + txtNum.Text + " "+cbxType.SelectedItem+ " 合计:" + totalPrices.ToString()); lblResult.Text = total.ToString(); }
第三章 单一职责原则
就一个类而言,应该仅有一个引起它变化的原因
第四章 开放-封闭原则
软件实体应该可以扩展,但是不可修改
第五章 依赖倒置原则
高层模块不应该依赖于低层模块。两个都应该依赖于抽象
抽象不应该依赖细节。细节应该依赖抽象
里氏替换原则:子类必须能够替换掉它们的父类
第六章 装饰模式
class Person { public Person() { } private string name; public Person(string name) { this.name = name; } public virtual void Show() { Console.WriteLine("装扮的{0}", name); } }
class Finery : Person { protected Person component; //打扮 public void Decorate(Person component) { this.component = component; } public override void Show() { if (component != null) { component.Show(); } } }
class TShirts : Finery { public override void Show() { Console.Write("大T恤 "); base.Show(); } } class BigTrouser : Finery { public override void Show() { Console.Write("垮裤 "); base.Show(); } } class Sneakers : Finery { public override void Show() { Console.Write("破球鞋 "); base.Show(); } }
客户端:
Person xc = new Person("小菜"); Console.WriteLine("\n第一种装扮:"); Sneakers pqx = new Sneakers(); BigTrouser kk = new BigTrouser(); TShirts dtx = new TShirts(); pqx.Decorate(xc); kk.Decorate(pqx); dtx.Decorate(kk); dtx.Show();
第七章 代理模式
class SchoolGirl { private string name; public string Name { get { return name; } set { name = value; } } }
//送礼物 interface GiveGift { void GiveDolls(); void GiveFlowers(); void GiveChocolate(); }
class Pursuit : GiveGift { SchoolGirl mm; public Pursuit(SchoolGirl mm) { this.mm = mm; } public void GiveDolls() { Console.WriteLine(mm.Name + " 送你洋娃娃"); } public void GiveFlowers() { Console.WriteLine(mm.Name + " 送你鲜花"); } public void GiveChocolate() { Console.WriteLine(mm.Name + " 送你巧克力"); } }
class Proxy : GiveGift { Pursuit gg; public Proxy(SchoolGirl mm) { gg = new Pursuit(mm); } public void GiveDolls() { gg.GiveDolls(); } public void GiveFlowers() { gg.GiveFlowers(); } public void GiveChocolate() { gg.GiveChocolate(); } }
客户端:
SchoolGirl jiaojiao = new SchoolGirl(); jiaojiao.Name = "李娇娇"; Proxy daili = new Proxy(jiaojiao); daili.GiveDolls(); daili.GiveFlowers(); daili.GiveChocolate();
第八章 工厂方法模式
/// <summary> /// 工厂方法 /// </summary> interface IFactory { Operation CreateOperation(); }
/// <summary> /// 专门负责生产“+”的工厂 /// </summary> class AddFactory : IFactory { public Operation CreateOperation() { return new OperationAdd(); } }
客户端:
IFactory operFactory = new AddFactory(); Operation oper = operFactory.CreateOperation(); oper.NumberA = 1; oper.NumberB = 2; double result=oper.GetResult();
第九章 原型模式
class Resume : ICloneable { public Object Clone() { return (Object)this.MemberwiseClone(); } }
Resume b = (Resume)a.Clone(); b.SetWorkExperience("1998-2006", "YY企业");
第十章 模版方法模式
第十一章 迪米特法则
最少知识原则
第十二章 外观模式
第十三章 建造者模式
第十四章 观察者模式
第十五章 抽象工厂模式
第十六章 状态模式
第十七章 适配器模式
第十八章 备忘录模式
class GameRole { //状态显示 public void StateDisplay() { Console.WriteLine("角色当前状态:"); Console.WriteLine("体力:{0}", this.vit); Console.WriteLine("攻击力:{0}", this.atk); Console.WriteLine("防御力:{0}", this.def); Console.WriteLine(""); } //保存角色状态 public RoleStateMemento SaveState() { return (new RoleStateMemento(vit, atk, def)); } //恢复角色状态 public void RecoveryState(RoleStateMemento memento) { this.vit = memento.Vitality; this.atk = memento.Attack; this.def = memento.Defense; } //获得初始状态 public void GetInitState() { this.vit = 100; this.atk = 100; this.def = 100; } //战斗 public void Fight() { this.vit = 0; this.atk = 0; this.def = 0; } }
//角色状态存储箱 class RoleStateMemento { private int vit; private int atk; private int def; public RoleStateMemento(int vit, int atk, int def) { this.vit = vit; this.atk = atk; this.def = def; } }
//角色状态管理者 class RoleStateCaretaker { private RoleStateMemento memento; public RoleStateMemento Memento { get { return memento; } set { memento = value; } } }
客户端:
//大战Boss前 GameRole lixiaoyao = new GameRole(); lixiaoyao.GetInitState(); lixiaoyao.StateDisplay(); //保存进度 RoleStateCaretaker stateAdmin = new RoleStateCaretaker(); stateAdmin.Memento = lixiaoyao.SaveState(); //大战Boss时,损耗严重 lixiaoyao.Fight(); lixiaoyao.StateDisplay(); //恢复之前状态 lixiaoyao.RecoveryState(stateAdmin.Memento);
第十九章 组合模式
第二十章 迭代器模式
第二十一章 单例模式
第二十二章 桥接模式
//手机软件 abstract class HandsetSoft { public abstract void Run(); }
//手机品牌 abstract class HandsetBrand { protected HandsetSoft soft; //设置手机软件 public void SetHandsetSoft(HandsetSoft soft) { this.soft = soft; } //运行 public abstract void Run(); }
第二十三章 命令模式
//烤肉串者 public class Barbecuer { public void BakeMutton() { Console.WriteLine("烤羊肉串!"); } public void BakeChickenWing() { Console.WriteLine("烤鸡翅!"); } }
//抽象命令 public abstract class Command { protected Barbecuer receiver; public Command(Barbecuer receiver) { this.receiver = receiver; } //执行命令 abstract public void ExcuteCommand(); }
//烤羊肉串命令 class BakeMuttonCommand : Command { public BakeMuttonCommand(Barbecuer receiver) : base(receiver) { } public override void ExcuteCommand() { receiver.BakeMutton(); } } //烤鸡翅命令 class BakeChickenWingCommand : Command { public BakeChickenWingCommand(Barbecuer receiver) : base(receiver) { } public override void ExcuteCommand() { receiver.BakeChickenWing(); } }
//服务员 public class Waiter { private IList<Command> orders = new List<Command>(); //设置订单 public void SetOrder(Command command) { if (command.ToString() == "命令模式.BakeChickenWingCommand") { Console.WriteLine("服务员:鸡翅没有了,请点别的烧烤。"); } else { orders.Add(command); Console.WriteLine("增加订单:" + command.ToString() + " 时间:" + DateTime.Now.ToString()); } } //取消订单 public void CancelOrder(Command command) { orders.Remove(command); Console.WriteLine("取消订单:" + command.ToString() + " 时间:" + DateTime.Now.ToString()); } //通知全部执行 public void Notify() { foreach (Command cmd in orders) { cmd.ExcuteCommand(); } } }
客户端:
//开店前的准备 Barbecuer boy = new Barbecuer(); Command bakeMuttonCommand1 = new BakeMuttonCommand(boy); Command bakeMuttonCommand2 = new BakeMuttonCommand(boy); Command bakeChickenWingCommand1 = new BakeChickenWingCommand(boy); Waiter girl = new Waiter(); //开门营业 顾客点菜 girl.SetOrder(bakeMuttonCommand1); girl.SetOrder(bakeMuttonCommand2); girl.SetOrder(bakeChickenWingCommand1); //点菜完闭,通知厨房 girl.Notify();
第二十四章 职责链模式
第二十五章 中介者模式
//联合国机构 abstract class UnitedNations { /// <summary> /// 声明 /// </summary> /// <param name="message">声明信息</param> /// <param name="colleague">声明国家</param> public abstract void Declare(string message, Country colleague); }
//联合国安全理事会 class UnitedNationsSecurityCouncil : UnitedNations { private USA colleague1; private Iraq colleague2; public USA Colleague1 { set { colleague1 = value; } } public Iraq Colleague2 { set { colleague2 = value; } } public override void Declare(string message, Country colleague) { if (colleague == colleague1) { colleague2.GetMessage(message); } else { colleague1.GetMessage(message); } } }
//国家 abstract class Country { protected UnitedNations mediator; public Country(UnitedNations mediator) { this.mediator = mediator; } }
//美国 class USA : Country { public USA(UnitedNations mediator) : base(mediator) { } //声明 public void Declare(string message) { mediator.Declare(message, this); } //获得消息 public void GetMessage(string message) { Console.WriteLine("美国获得对方信息:" + message); } } //伊拉克 class Iraq : Country { public Iraq(UnitedNations mediator) : base(mediator) { } //声明 public void Declare(string message) { mediator.Declare(message, this); } //获得消息 public void GetMessage(string message) { Console.WriteLine("伊拉克获得对方信息:" + message); } }
客户端:
UnitedNationsSecurityCouncil UNSC = new UnitedNationsSecurityCouncil(); USA c1 = new USA(UNSC); Iraq c2 = new Iraq(UNSC); UNSC.Colleague1 = c1; UNSC.Colleague2 = c2; c1.Declare("不准研制核武器,否则要发动战争!"); c2.Declare("我们没有核武器,也不怕侵略。");
第二十六章 享元模式
第二十七章 解释器模式
第二十八章 访问者模式
//人 abstract class Person { //接受 public abstract void Accept(Action visitor); } //男人 class Man : Person { public override void Accept(Action visitor) { visitor.GetManConclusion(this); } } //女人 class Woman : Person { public override void Accept(Action visitor) { visitor.GetWomanConclusion(this); } }
//状态 abstract class Action { //得到男人结论或反应 public abstract void GetManConclusion(Man concreteElementA); //得到女人结论或反应 public abstract void GetWomanConclusion(Woman concreteElementB); }
//成功 class Success : Action { public override void GetManConclusion(Man concreteElementA) { Console.WriteLine("{0}{1}时,背后多半有一个伟大的女人。", concreteElementA.GetType().Name, this.GetType().Name); } public override void GetWomanConclusion(Woman concreteElementB) { Console.WriteLine("{0}{1}时,背后大多有一个不成功的男人。", concreteElementB.GetType().Name, this.GetType().Name); } }
//对象结构 class ObjectStructure { private IList<Person> elements = new List<Person>(); //增加 public void Attach(Person element) { elements.Add(element); } //移除 public void Detach(Person element) { elements.Remove(element); } //查看显示 public void Display(Action visitor) { foreach (Person e in elements) { e.Accept(visitor); } } }
客户端:
ObjectStructure o = new ObjectStructure(); o.Attach(new Man()); o.Attach(new Woman()); Success v1 = new Success(); o.Display(v1);