大话设计模式 (程杰 著)

第1章 代码无错就是优?        [简单工厂模式] (已看)算法

第2章 商场促销             [策略模式]  (已看)编程

第3章 拍摄UFO             [单一职责原则]  (已看)ide

第4章 考研求职两不误          [开放-封闭原则]  (已看)函数

第5章 会修电脑不会修收音机?     [依赖倒转原则]  (已看)ui

第6章 穿什么有这么重要?       [装饰模式]  (已看)this

第7章 为别人作嫁衣           [代理模式]  (已看)spa

第8章 雷锋依然在人间          [工厂方法模式]  (已看)翻译

第9章 简历复印             [原型模式]  (已看)设计

第10章 考题抄错会作也白搭      [模板方法模式]  (已看)代理

第11章 无熟人难办事?          [迪米特法则]  (已看)

第12章 牛市股票还会亏钱?        [外观模式]  (已看)

第13章 好菜每回味不一样        [建造者模式]  (已看)

第14章 老板回来,我不知道         [观察者模式]  (已看)

第15章 就不能不换DB模式         [抽象工厂模式]  (已看)

第16章 无尽加班什么时候休         [状态模式]  (已看)

第17章 在NBA我须要翻译        [适配器模式]  (已看)

第18章 若是再回到从前         [备忘录模式]  (已看)

第19章 分公司=一部门          [组合模式]  (已看)

第20章 想走?能够!先买票           [迭代器模式]  (已看)

第21章 有些类也须要计划生育      [单例模式]  (已看)

第22章 手机软件什么时候统一        [桥接模式]  (已看)

第23章 烤羊肉串引来的思考       [命令模式]  (已看)

第24章 加薪非要老总批?         [职责链模式] (已看)

第25章 世界须要和平            [中介者模式] (已看)

第26章 项目多也别傻作         [享元模式] (已看)

第27章 其实你不懂老板的心       [解释器模] (已看)

第28章 男人和女人          [访问者模] (已看)

第29章 OOTV杯超级模式大赛      [模式总结] (已看)   

 

 

第1章 代码无错就是优?        [简单工厂模式]

using System;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            Operation opAdd = OperationFactory.CreateOperate("+");
            opAdd.NumberA = 1;
            opAdd.NumberB = 2;
            Console.WriteLine(opAdd.GetResult());

            Operation opSub = OperationFactory.CreateOperate("-");
            opSub.NumberA = 1;
            opSub.NumberB = 2;
            Console.WriteLine(opSub.GetResult());
        }
    }

    public abstract class Operation {
        private double numberA = 0;
        private double numberB = 0;

        public double NumberA {
            get { return numberA; }
            set { numberA = value; }
        }

        public double NumberB {
            get { return numberB; }
            set { numberB = value; }
        }

        public virtual double GetResult() {
            double result = 0;
            return result;
        }
    }

    public class OperationAdd : Operation {
        public override double GetResult() {
            return NumberA + NumberB;
        }
    }

    public class OperationSub : Operation {
        public override double GetResult() {
            return NumberA - NumberB;
        }
    }


    public class OperationFactory {
        public static Operation CreateOperate(string operate) {
            Operation oper = null;
            switch (operate) {
                case "+":
                    oper = new OperationAdd();
                    break;
                case "-":
                    oper = new OperationSub();
                    break;
            }

            return oper;
        }
    }
}
View Code

聚合表示一种弱的'拥有'关系,体现的是A对象能够包含B对象,但B对象不是A对象的一部分

合成(Composition,也有翻译成'组合'的)是一种强的'拥有'关系,体现了严格的部分和总体的关系,部分和总体的生命周期同样

第2章 商场促销             [策略模式]

using System;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            int condition = 2;
            CashContext cashContext = null;

            switch (condition) {
                case 1:
                    cashContext = new CashContext(new CashNormal());
                    break;
                case 2:
                    cashContext = new CashContext(new CashDiscount(0.8));
                    break;
            }

            Console.WriteLine(cashContext.getResult(100));
        }
    }


    public class CashContext {
        private CashSuper cashSuper = null;

        public CashContext(CashSuper cashSuper) {
            this.cashSuper = cashSuper;
        }

        public double getResult(double money) {
            return cashSuper.acceptCash(money);
        }
    }
    
    
    public abstract class CashSuper {
        public abstract double acceptCash(double money);
    }

    public class CashNormal : CashSuper {
        public override double acceptCash(double money) {
            return money;
        }
    }

    public class CashDiscount : CashSuper {
        private double discount;

        public CashDiscount(double discount) {
            this.discount = discount;
        } 
        
        public override double acceptCash(double money) {
            return money * discount;
        }
    }
}
View Code

[策略模式(Strategy)它定义了算法家族,分别封装起来,让它们之间能够互相替换,此模式让算法的变化,不会影响到使用算法的客户]

面向对象的编程,并非类越多越好,类的划分是为了封装,但分类的基础是抽象,具备相同属性和功能的对象的抽象集合才是类.

第3章 拍摄UFO             [单一职责原则]

[单一职责原则(SRP)]就一个类而言,应该仅有一个引发它变化的缘由.

若是一个类承担的职责过多,就等于把这些职责耦合在一块儿,一个职责的变化可能会削弱或者抑制这个类完成其余职责的能力.

这种耦合会致使脆弱的设计,当变化发生时,设计会遭受到意想不到的破坏

软件设计真正要作的许多内容,就是发现职责并把那些职责相互分离.

若是你可以想到多于一个动机去改变一个类,那么这个类就具备多于一个的职责

第4章 考研求职两不误          [开放-封闭原则]

[开放-封闭原则]是说软件实体(类,模块,函数等等)应该能够扩展,可是不可修改

不管模块是多么的'封闭',都会存在一些没法对之封闭的变化.既然不可能彻底封闭,设计人员必须对于他设计的模块应该对哪一种变化封闭作出选择。

他必须先猜想出最有可能发生的变化种类,而后构造抽象来隔离那些变化.

等到变化发生时当即采起行动

在咱们最初编写代码时,假设变化不会发生.当变化发生时,咱们就建立抽象来隔离之后发生的同类变化

面对需求,对程序的改动是经过增长新代码进行的,而不是更改现有的代码

咱们但愿的是在开发工做展开不久就知道可能发生的变化.查明可能发生的变化所等待的时间越长,要建立正确的抽象就越困难

开放-封闭原则是面向对象设计的核心所在.遵循这个原则能够带来面向对象技术所声称的巨大好处,也就是可维护,可扩展,可复用,灵活性好.

开发人员应该仅对程序中呈现出频繁变化的那些部分作出抽象,然而,对于应用程序中的每一个部分都刻意地进行抽象一样不是一个好主意》

拒毫不成熟的抽象和抽象自己同样重要

第5章 会修电脑不会修收音机?     [依赖倒转原则]

[依赖倒置原则]A.高层模块不该该依赖低层模块.两个都应该依赖抽象.B.抽象不该该依赖细节.细节应该依赖抽象.

针对接口编程,不要对实现编程.

[里氏代换原则]子类型必须可以替换掉它们的父类型

一个软件实体若是使用的是一个父类的话,那么必定适用于其子类,并且它察觉不出父类对象和子类对象的区别.

也就是说,在软件里面,把父类都替换成它的子类,程序的行为没有变化

只有当子类能够替换掉父类,软件单位的功能不受到影响时,父类才能真正被复用,而子类也可以在父类的基础上增长新的行为

因为子类型的可替换性才使得使用父类类型的模块在无需修改的状况下就能够扩展

依赖倒转其实能够说是面向对象设计的标志,用哪一种语言来编写程序不重要,若是编写时考虑的都是如何针对抽象编程而不是针对细节编程,

即程序中全部的依赖关系都是终止于抽象类或者接口,那就是面向对象的设计,反之那就是过程化的设计了.

第6章 穿什么有这么重要?       [装饰模式]

using System;



namespace ConsoleApplication1 {
    public class Program {
        public static void Main(string[] args) {
            ConcreteComponent c = new ConcreteComponent();
            ConcreteDecoratorA d1 = new ConcreteDecoratorA();
            ConcreteDecoratorB d2 = new ConcreteDecoratorB();

            d1.SetComponent(c);
            d2.SetComponent(d1);
            d2.Operation();
        }
    }

    public abstract class Component {
        public abstract void Operation();
    }

    public class ConcreteComponent : Component {
        public override void Operation() {
            Console.WriteLine("具体对象的操做");
        }
    }


    public abstract class Decorator : Component {

        public Component component;

        public void SetComponent(Component component) {
            this.component = component;
        }
        
        public override void Operation() {
            if (component != null) {
                component.Operation();    
            }
        }
    }

    public class ConcreteDecoratorA : Decorator {
        private string addedState;

        public override void Operation() {
            base.Operation();
            addedState = "New State";
            Console.WriteLine("具体装饰对象A的操做");
        }
    }

    public class ConcreteDecoratorB : Decorator {
        public override void Operation() {
            base.Operation();
            AddedBehavior();
            Console.WriteLine("具体装饰对象B的操做");
        }

        private void AddedBehavior() {
            
        }
    }
    
}
View Code

[装饰模式(Decorator)]动态地给一个对象添加一些额外的职责,就增长功能来讲,装饰模式比生成子类更为灵活

第7章 为别人作嫁衣           [代理模式]

using System;

namespace ConsoleApplication1 {
    public class Program {
        public static void Main(string[] args) {
            Proxy proxy = new Proxy();
            proxy.Request();
            
        }
    }

    public abstract class Subject {
        public abstract void Request();
    }

    public class RealSubject : Subject {
        public override void Request() {
            Console.WriteLine("真实的请求");
        }
    }

    public class Proxy : Subject {
        private RealSubject realSubject;


        public override void Request() {
            if (realSubject == null) {
                realSubject = new RealSubject();
            }
            
            realSubject.Request();
        }
    }
}
View Code

[代理模式(Proxy)]为其余对象提供一种代理以控制对这个对象的访问

第8章 雷锋依然在人间          [工厂方法模式]

using System;

namespace ConsoleApplication1 {
    public class Program {
        public static void Main(string[] args) {
            IFactory factory = new AddFactory();
            
            Operation operation = factory.CreateOperation();
            operation.NumberA = 1;
            operation.NumberB = 2;
            
            Console.WriteLine(operation.GetResult());

        }
    }

    public abstract class Operation {
        private double numberA = 0;
        private double numberB = 0;

        public double NumberA {
            get { return numberA; }
            set { numberA = value; }
        }

        public double NumberB {
            get { return numberB; }
            set { numberB = value; }
        }

        public virtual double GetResult() {
            double result = 0;
            return result;
        }
    }

    public class OperationAdd : Operation {
        public override double GetResult() {
            return NumberA + NumberB;
        }
    }

    public class OperationSub : Operation {
        public override double GetResult() {
            return NumberA - NumberB;
        }
    }

    public interface IFactory {
        Operation CreateOperation();
    }

    public class AddFactory : IFactory {
        public Operation CreateOperation() {
            return new OperationAdd();
        }
    }

    public class SubFactory : IFactory {
        public Operation CreateOperation() {
            return new OperationSub();
        }
    }
    
}
View Code

[工厂方法模式(Factory Method)]定义一个用于建立对象的接口,让子类决定实例化哪个类.工厂方法使一个类的实例化延迟到其子类.

第9章 简历复印             [原型模式]

using System;
using System.Net.Security;

namespace ConsoleApplication1 {
    public class Program {
        public static void Main(string[] args) {
            ConcretePrototype1 p1 = new ConcretePrototype1("I");
            ConcretePrototype1 c1 = (ConcretePrototype1) p1.Clone();
            Console.WriteLine("Cloned: {0}",c1.Id);
            
        }
    }

    public abstract class Prototype {
        private string id;

        public Prototype(string id) {
            this.id = id;
        }

        public string Id {
            get { return id; }
        }

        public abstract Prototype Clone();
    }

    public class ConcretePrototype1 : Prototype {
        public ConcretePrototype1(string id) : base(id) {

        }

        public override Prototype Clone() {
            return (Prototype)this.MemberwiseClone();
        }
    }

    public class ConcretePrototype2 : Prototype {
        public ConcretePrototype2(string id) : base(id) {
            
        }

        public override Prototype Clone() {
            return (Prototype)this.MemberwiseClone();
        }
    }
}
View Code

[原型模式(Prototype)]用原型实例指定建立对象的种类,而且经过拷贝这些原型建立新的对象

第10章 考题抄错会作也白搭      [模板方法模式]

using System;
using System.Diagnostics.CodeAnalysis;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            AbstractClass c;
            c = new ConcreteClassA();
            c.TemplateMethod();
            
            c = new ConcreteClassB();
            c.TemplateMethod();            
        }
    }

    public abstract class AbstractClass {
        public abstract void PrimitiveOperation1();
        public abstract void PrimitiveOperation2();

        public void TemplateMethod() {
            PrimitiveOperation1();
            PrimitiveOperation2();
            Console.WriteLine("");
        }
    }

    public class ConcreteClassA : AbstractClass {
        public override void PrimitiveOperation1() {
            Console.WriteLine("具体类A方法1的实现");
        }

        public override void PrimitiveOperation2() {
            Console.WriteLine("具体类A方法2的实现");
        }
    }

    public class ConcreteClassB : AbstractClass {
        public override void PrimitiveOperation1() {
            Console.WriteLine("具体类B方法1的实现");
        }

        public override void PrimitiveOperation2() {
            Console.WriteLine("具体类B方法2的实现");
        }
    }
}
View Code

[模板方法模式]定义一个操做中的算法的骨架,而将一些步骤延迟到子类中.模板方法使得子类能够不改变一个算法的结构既可重定义该算法的某些特定步骤.

第11章 无熟人难办事?          [迪米特法则]

[迪米特法则(LoD)]若是两个类没必要彼此直接通讯,那么这两个类就不该当发生直接的做用.若是其中一个类须要调用另外一个类的某一个方法的话,能够经过第三者转发这个调用.

在类的结构设计上,每个类都应当尽可能下降成员的访问权限.

迪米特法则其根本思想,是强调了类之间的松耦合.

类之间的耦合越弱,越有利于复用,一个处在弱耦合的类被修改,不会对有关系的类形成波及.

第12章 牛市股票还会亏钱?        [外观模式]

using System;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            Facade facade = new Facade();
            facade.MethodA();
            facade.MethodB();                        
        }
    }

    public class SubSystemOne {
        public void MethodOne() {
            Console.WriteLine("子系统方法一");
        }
    }

    public class SubSystemTwo {
        public void MethodTwo() {
            Console.WriteLine("子系统方法二");
        }
    }

    public class SubSystemThree {
        public void MethodThree() {
            Console.WriteLine("子系统方法三");
        }
    }

    public class SubSystemFour {
        public void MethodFour() {
            Console.WriteLine("子系统方法四");
        }
    }

    public class Facade {
        private SubSystemOne one;
        private SubSystemTwo two;
        private SubSystemThree three;
        private SubSystemFour four;

        public Facade() {
            one = new SubSystemOne();
            two = new SubSystemTwo();
            three = new SubSystemThree();
            four = new SubSystemFour();
        }

        public void MethodA() {
            Console.WriteLine("\n方法组A() ---- ");
            one.MethodOne();
            two.MethodTwo();
            four.MethodFour();
        }

        public void MethodB() {
            Console.WriteLine("\n方法组B() ---- ");
            two.MethodTwo();
            three.MethodThree();
        }
    }
}
View Code

[外观模式(Facade)]为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用

首先,在设计初期阶段,应该要有意识的将不一样的两个层分离.

其次,在开发阶段,子系统每每由于不断的重构演化而变得愈来愈复杂,增长外观Facade能够提供一个简单的接口,减小它们之间的依赖.

第三,在维护一个遗留的大型系统时,可能这个系统已经很是难以维护和扩展了,为新系统开发一个外观Facade类,来提供设计粗糙或高度复杂的遗留代码的比较清晰简单的接口,

   让新系统与Facade对象交互,Facade与遗留代码交互全部复杂的工做.

第13章 好菜每回味不一样        [建造者模式]

using System;
using System.Collections.Generic;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            Director director = new Director();
            
            Builder b1 = new ConcreteBuilder1();
            Builder b2 = new ConcreteBuilder2();
            
            director.Construct(b1);
            Product p1 = b1.GetResult();
            p1.Show();
            
            director.Construct(b2);
            Product p2 = b2.GetResult();
            p2.Show();
        }
    }

    public class Product {
        private IList<string> parts = new List<string>();

        public void Add(string part) {
            parts.Add(part);
        }

        public void Show() {
            Console.WriteLine("\n产品 建立 ----");
            foreach (string part in parts) {
                Console.WriteLine(part);
            }
        }
    }

    public abstract class Builder {
        public abstract void BuildPartA();
        public abstract void BuildPartB();
        public abstract Product GetResult();
    }
    
    public class ConcreteBuilder1 : Builder {
        private Product product = new Product();

        public override void BuildPartA() {
            product.Add("部件A");
        }

        public override void BuildPartB() {
            product.Add("部件B");
        }

        public override Product GetResult() {
            return product;
        }
    }

    public class ConcreteBuilder2 : Builder {
        private Product product = new Product();

        public override void BuildPartA() {
            product.Add("部件X");
        }

        public override void BuildPartB() {
            product.Add("部件Y");
        }

        public override Product GetResult() {
            return product;
        }
    }

    public class Director {
        public void Construct(Builder builder) {
            builder.BuildPartA();
            builder.BuildPartB();
        }
    }
}
View Code

[建造者模式(Builder)]将一个复杂对象的构建与它的表示分离,使得一样的构建过程能够建立不一样的表示

第14章 老板回来,我不知道         [观察者模式]

using System;
using System.Collections.Generic;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            ConcreteSubject s = new ConcreteSubject();
            s.Attach(new ConcreteObserver(s, "X"));
            s.Attach(new ConcreteObserver(s, "Y"));
            s.Attach(new ConcreteObserver(s,"Z"));


            s.SubjectState = "123";
            s.Notify();

            s.SubjectState = "ABC";
            s.Notify();
        }
    }

    public abstract class Subject {
        private IList<Observer> observers = new List<Observer>();

        public void Attach(Observer observer) {
            observers.Add(observer);
        }

        public void Detach(Observer observer) {
            observers.Remove(observer);
        }

        public void Notify() {
            foreach (Observer o in observers) {
                o.Update();
            }
        }
    }

    public class ConcreteSubject : Subject {
        private string subjectState;

        public string SubjectState {
            get { return subjectState;}
            set { subjectState = value; }
        }
    }
    
    public abstract class Observer {
        public abstract void Update();
    }

    public class ConcreteObserver : Observer {

        private string name;
        private string observerState;
        private ConcreteSubject subject;

        public ConcreteObserver(ConcreteSubject subject, string name) {
            this.subject = subject;
            this.name = name;
        }
        
        public override void Update() {
            observerState = subject.SubjectState;
            Console.WriteLine("观察者{0}的新状态是{1}", name, observerState);
        }

        public ConcreteSubject Subject {
            get { return subject; }
            set { subject = value; }
        }
    }
}
View Code

[观察者模式]定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象.这个主题对象在状态发生变化时,会通知全部观察者对象,使它们可以自动更新本身

将一个系统分割成一系列相互协做的类有一个很很差的反作用,那就是须要维护相关对象间的一致性.咱们不但愿为了维持一致性而使各种紧密耦合,这样会给维护,扩展和重用都带来不便

观察者模式所作的工做其实就是在解除耦合.让耦合的双方都依赖于抽象,而不是依赖于具体.从而使得各自的变化都不会影响另外一边的变化.

第15章 就不能不换DB模式         [抽象工厂模式]

using System;

namespace ConsoleApplication1 {
    public class Program {
        public static void Main(string[] args) {
            User user = new User();
            Department department = new Department();
            
            IFactory factory = new AccessFactory();
            IUser iuser = factory.CreateUser();
            iuser.Insert(user);
            iuser.GetUser(1);
            IDepartment idepartment = factory.CreateDepartment();
            idepartment.Insert(department);
            idepartment.GetDepartment(1);

        }
    }

    public class User {
        public int ID { get; set; }
    }

    public class Department {
        public int ID { get; set; }
    }


    public interface IUser {
        void Insert(User user);
        User GetUser(int id);
    }

    public class SqlServerUser : IUser {
        public void Insert(User user) {
            Console.WriteLine("在SQL Server中给User表增长一条记录");
        }

        public User GetUser(int id) {
            Console.WriteLine("在SQL Server中根据ID获得User表的一条记录");
            return null;
        }   
    }

    public class AccessUser : IUser {
        public void Insert(User user) {
            Console.WriteLine("在Acces中给User表增长一条记录");
        }

        public User GetUser(int id) {
            Console.WriteLine("在Access中根据ID获得User表的一条记录");
            return null;
        }
    }

    public interface IDepartment {
        void Insert(Department department);
        Department GetDepartment(int id);
    }

    public class SqlServerDepartment : IDepartment {
        public void Insert(Department department) {
            Console.WriteLine("在SQL Server中给Department表增长一条记录");
        }

        public Department GetDepartment(int id) {
            Console.WriteLine("在SQL Server中根据ID获得Department表的一条记录");
            return null;
        }
    }

    public class AccessDepartment : IDepartment {
        public void Insert(Department department) {
            Console.WriteLine("在Acces中给Department表增长一条记录");
        }

        public Department GetDepartment(int id) {
            Console.WriteLine("在Access中根据ID获得Department表的一条记录");
            return null;
        }
    }

    public interface IFactory {
        IUser CreateUser();
        IDepartment CreateDepartment();
    }

    public class SqlServerFactory : IFactory {
        public IUser CreateUser() {
            return new SqlServerUser();
        }

        public IDepartment CreateDepartment() {
            return new SqlServerDepartment();
        }
    }


    public class AccessFactory : IFactory {
        public IUser CreateUser() {
            return new AccessUser();
        }

        public IDepartment CreateDepartment() {
            return new AccessDepartment();
        }
    }
}
View Code

[抽象工厂模式(Abstract Factory)]提供一个建立一系列相关或相互依赖对象的接口,而无需指定它们具体的类

第16章 无尽加班什么时候休         [状态模式]

using System;
using System.Collections.Generic;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            Work work = new Work();
            work.Hour = 9;
            work.WriteProgram();
            work.Hour = 10;
            work.WriteProgram();
            work.Hour = 12;
            work.WriteProgram();
            work.Hour = 13;
            work.WriteProgram();
            work.Hour = 14;
            work.WriteProgram();
            work.Hour = 17;
            work.TaskFinished = false;
            work.WriteProgram();
            work.Hour = 19;
            work.WriteProgram();
            work.Hour = 22;
            work.WriteProgram();
        }
    }

    
    
    public abstract class State {
        public abstract void WriteProgram(Work w);
    }

    public class ForenoonState : State {
        public override void WriteProgram(Work w) {
            if (w.Hour < 12) {
                Console.WriteLine("当前时间: {0}点 上午工做,精神百倍",w.Hour);
            } else {
                w.SetState(new NoonState());
                w.WriteProgram();
            }
        }
    }

    public class NoonState : State {
        public override void WriteProgram(Work w) {
            if (w.Hour < 13) {
                Console.WriteLine("当前时间: {0}点 饿了,午餐:犯困,午休.",w.Hour);
            } else {
                w.SetState(new AfternoonState());
                w.WriteProgram();
            }
        }
    }

    public class AfternoonState : State {
        public override void WriteProgram(Work w) {
            if (w.Hour < 17) {
                Console.WriteLine("当前时间: {0}点 下午状态还不错,继续努力",w.Hour);
            } else {
                w.SetState(new EveningState());
                w.WriteProgram();
            }
        }
    }

    public class EveningState : State {
        public override void WriteProgram(Work w) {
            if (w.TaskFinished) {
                w.SetState(new RestState());
                w.WriteProgram();
            } else {
                if (w.Hour < 21) {
                    Console.WriteLine("当前时间: {0}点 加班哦,疲惫之极",w.Hour);
                } else {
                    w.SetState(new SleepingState());
                    w.WriteProgram();
                }
            }
        }
    }

    public class SleepingState : State {
        public override void WriteProgram(Work w) {
            Console.WriteLine("当前时间: {0}点 不行了,睡着了.",w.Hour);
        }
    }

    public class RestState : State {
        public override void WriteProgram(Work w) {
            Console.WriteLine("当前时间: {0}点 下班回家了",w.Hour);
        }
    }


    public class Work {
        private State current;
        private double hour;
        private bool finish = false;
        
        public Work() {
            current = new ForenoonState();
        }

        public double Hour {
            get { return hour; }
            set { hour = value; }
        }

        public bool TaskFinished {
            get { return finish; }
            set { finish = value; }
        }

        public void SetState(State s) {
            current = s;
        }

        public void WriteProgram() {
            current.WriteProgram(this);
        }
    }
}
View Code

[状态模式(State)]当一个对象的内在状态改变时容许改变其行为,这个对象看起来像是改变了其类

状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的状况.

把状态的判断逻辑转移到表示不一样状态的一系列类当中,能够把复杂的判断逻辑简化

第17章 在NBA我须要翻译        [适配器模式]

using System;
using System.Collections.Generic;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            
            Target target = new Target();
            target.Request();
            
            Target adapter = new Adapter();
            adapter.Request();
        }
    }

    public class Target {
        public virtual void Request() {
            Console.WriteLine("普通请求!");
        }
    }

    public class Adaptee {
        public void SepcificRequest() {
            Console.WriteLine("特殊请求!");
        }
    }

    public class Adapter : Target {
        private Adaptee adaptee = new Adaptee();

        public override void Request() {
            adaptee.SepcificRequest();
        }
    }

}
View Code

[适配器模式(Adapter)]将一个类的接口转换成客户但愿的另一个接口.Adapter模式使得本来因为接口不兼容而不能一块儿工做的那些类能够一块儿工做

第18章 若是再回到从前         [备忘录模式]

using System;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            Originator o = new Originator();
            o.State = "On";
            o.Show();
            
            Caretaker c = new Caretaker();
            c.Memento = o.CreateMemento();

            o.State = "Off";
            o.Show();
            
            o.SetMemento(c.Memento);
            o.Show();
        }
    }

    public class Originator {
        private string state;

        public string State {
            get { return state; }
            set { state = value; }
        }

        public Memento CreateMemento() {
            return new Memento(state);
        }

        public void SetMemento(Memento memento) {
            state = memento.State;
        }

        public void Show() {
            Console.WriteLine("State="+ state);
        }
    }

    public class Memento {
        private string state;

        public Memento(string state) {
            this.state = state;
        }

        public string State {
            get { return state; }
        }
    }

    public class Caretaker {
        private Memento memento;

        public Memento Memento {
            get { return memento; }
            set { memento = value; }
        }
    }
}
View Code

[备忘录(Memento)]在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象以外保存这个状态.这样之后就可将该对象恢复到原先保存的状态.

第19章 分公司=一部门          [组合模式]

using System;
using System.Collections.Generic;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            Composite root = new Composite("root");
            root.Add(new Leaf("Leaf A"));
            root.Add(new Leaf("Leaf B"));
            
            Composite comp = new Composite("Composite X");
            comp.Add(new Leaf("Leaf XA"));
            comp.Add(new Leaf("Leaf XB"));
            
            Composite comp2 = new Composite("Composite XX");
            comp2.Add(new Leaf("Leaf XXA"));
            comp2.Add(new Leaf("Leaf XXB"));
            comp.Add(comp2);
            
            root.Add(comp);
            
            root.Add(new Leaf("Leaf C"));
            
            Leaf leaf = new Leaf("Leaf D");
            root.Add(leaf);
            root.Remove(leaf);
            
            root.Display(1);
            
            
        }
    }


    public abstract class Component {
        protected string name;

        public Component(string name) {
            this.name = name;
        }

        public abstract void Add(Component c);
        public abstract void Remove(Component c);
        public abstract void Display(int depth);
    }

    public class Leaf : Component {

        public Leaf(string name) : base(name) {
            
        }
        
        public override void Add(Component c) {
            Console.WriteLine("Can't add to a leaf");
        }

        public override void Remove(Component c) {
            Console.WriteLine("Can't remove from a leaf");
        }

        public override void Display(int depth) {
            Console.WriteLine(new string('-',depth) + name);
        }
    }


    public class Composite : Component {
        private List<Component> children = new List<Component>();

        public Composite(string name) : base(name) {
            
        }

        public override void Add(Component c) {
            children.Add(c);
        }

        public override void Remove(Component c) {
            children.Remove(c);
        }

        public override void Display(int depth) {
            Console.WriteLine(new string('-',depth) + name);

            foreach (Component component in children) {
                component.Display(depth + 2);
            }
        }
        
    }
}
View Code

[组合模式(Composite)]将对象组合成树形结构以表示'部分-总体'的层次结构.组合模式使得用户对单个对象和组合对象的使用具备一致性

第20章 想走?能够!先买票           [迭代器模式]

using System;
using System.Collections.Generic;

namespace ConsoleApplication1 {
    public class Program {
        public static void Main(string[] args) {
            ConcreteAggregate a = new ConcreteAggregate();

            a[0] = "大鸟";
            a[1] = "小菜";
            a[2] = "行李";
            a[3] = "老外";
            a[4] = "公交内部员工";
            a[5] = "小偷";

            Iterator i = new ConcreteIterator(a);
            object item = i.First();
            while (!i.IsDone()) {
                Console.WriteLine("{0} 请买车票!",i.CurrentItem());
                i.Next();
            }
        }
    }


    public abstract class Iterator {
        public abstract object First();
        public abstract object Next();
        public abstract bool IsDone();
        public abstract object CurrentItem();
    }

    public abstract class Aggregate {
        public abstract Iterator CreateIterator();
    }

    public class ConcreteIterator : Iterator {

        private ConcreteAggregate aggregate;
        private int current = 0;

        public ConcreteIterator(ConcreteAggregate aggregate) {
            this.aggregate = aggregate;
        }

        public override object First() {
            return aggregate[0];
        }

        public override object Next() {
            object ret = null;
            current++;
            if (current < aggregate.Count) {
                ret = aggregate[current];
            }

            return ret;
        }

        public override bool IsDone() {
            return current >= aggregate.Count ? true : false;
        }

        public override object CurrentItem() {
            return aggregate[current];
        }
    }


    public class ConcreteAggregate : Aggregate {
        public IList<object> items = new List<object>();

        public override Iterator CreateIterator() {
            return new ConcreteIterator(this);
        }

        public int Count {
            get { return items.Count; }
        }

        public object this[int index] {
            get { return items[index]; }
            set { items.Insert(index, value); }
        }
    }
}
View Code

[迭代器模式(Iterator)]提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示

第21章 有些类也须要计划生育      [单例模式]

using System;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            Singleton s1 = Singleton.GetInstance();
            Singleton s2 = Singleton.GetInstance();

            if (s1 == s2) {
                Console.WriteLine("两个对象是相同的实例");
            }
            
        }
    }


    public class Singleton {
        private static Singleton instance;

        private Singleton() {
            
        }

        public static Singleton GetInstance() {
            if (instance == null) {
                instance = new Singleton();
            }

            return instance;
        }
    }

}
View Code

[单例模式(Singleton)]保证一个类仅有一个实例,并提供一个访问它的全局访问点

一般咱们可让一个全局变量使得一个对象被访问,但它不能防止你实例化多个对象.一个最好的办法就是,

让类自身负责保存它的惟一实例.这个类能够保证没有其余实例能够被建立,而且它能够提供一个访问该实例的方法

第22章 手机软件什么时候统一        [桥接模式]

using System;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            Abstraction ab = new RefinedAbstraction();
            ab.SetImplementor(new ConcreteImplementorA());
            ab.Operation();
            
            ab.SetImplementor(new ConcreteImplementorB());
            ab.Operation();
        }
    }

    public abstract class Implementor {
        public abstract void Operation();
    }

    public class ConcreteImplementorA : Implementor {
        public override void Operation() {
            Console.WriteLine("具体实现A的方法执行");
        }
    }

    public class ConcreteImplementorB : Implementor {
        public override void Operation() {
            Console.WriteLine("具体实现B的方法执行");
        }
    }

    public class Abstraction {
        protected Implementor implementor;

        public void SetImplementor(Implementor implementor) {
            this.implementor = implementor;
        }

        public virtual void Operation() {
            implementor.Operation();
        }
    }

    public class RefinedAbstraction : Abstraction {
        public override void Operation() {
            implementor.Operation();
        }
    }
}
View Code

[桥接模式(Bridge)]将抽象部分与它的实现部分分离,使它们均可以独立地变化

什么叫抽象与它的实现分离,这并非说,让抽象类与其派生类分离,由于这没有任何意义.

实现指的是抽象类和它的派生类用来实现本身的对象

[合成/聚合复用原则(CARP)]尽可能使用合成/聚合,尽可能不要使用类继承

聚合表示一种弱的"拥有"关系,体现的是A对象能够包含B对象,但B对象不是A对象的一部分;合成则是一种强的"拥有“关系,

体现了严格的部分和总体的关系,部分和总体的生命周期同样.

合成/聚合复用原则的好处是:优先使用对象的合成/聚合将有助于你保持每一个类被封装,并被集中在单个任务上.

这样类和类继承层次会保持较小规模,而且不太可能增加为不可控制的庞然大物

对象的继承关系是在编译时就定义好了,因此没法在运行时改变从父类继承的实现.

子类的实现与它的父类有很是紧密的依赖关系,以致于父类实现中的任何变化必然会致使子类发生变化.

当你须要复用子类时,若是继承下来的实现不适合解决新的问题,则父类必须重写或被其余更适合的类替换.

这种依赖关系限制了灵活性并最终限制了复用性

第23章 烤羊肉串引来的思考       [命令模式]

using System;
using System.Collections.Generic;

namespace ConsoleApplication1 {
    public class Program {
        public static void Main(string[] args) {
            Receiver r = new Receiver();
            Command c = new ConcreteCommand(r);
            Invoker i = new Invoker();
            i.SetCommand(c);
            i.ExecuteCommand();
        }
    }
    
    

    public abstract class Command {
        protected Receiver receiver;

        public Command(Receiver receiver) {
            this.receiver = receiver;
        }

        public abstract void Execute();
    }

    public class ConcreteCommand : Command {
        public ConcreteCommand(Receiver receiver) : base(receiver) {
            
        }

        public override void Execute() {
            receiver.Action();
        }
    }

    public class Receiver {
        public void Action() {
            Console.WriteLine("执行请求!");
        }
    }

    public class Invoker {
        private Command command;

        public void SetCommand(Command command) {
            this.command = command;
        }

        public void ExecuteCommand() {
            command.Execute();
        }
    }
}
View Code

[命令模式(Command)]将一个请求封装为一个对象,从而使你可用不一样的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操做

敏捷开发原则告诉咱们,不要为代码添加基于猜想的,实际不须要的功能.若是不清楚一个系统是否须要命令模式,通常就不要着急去实现它,

事实上,在须要的时候经过重构实现这个模式并不困难,只有在真正须要如撤销/恢复操做等功能时,把原来的代码重构为命令模式才有意义

第24章 加薪非要老总批?         [职责链模式]

using System;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            Handler h1 = new ConcreteHandler1();
            Handler h2 = new ConcreteHandler2();
            Handler h3 = new ConcreteHandler3();
            h1.SetSuccessor(h2);
            h2.SetSuccessor(h3);

            int[] requests = {2, 15, 14, 22, 18, 3, 27, 20};

            foreach (int request in requests) {
                h1.HandleRequest(request);
            }
        }
    }

    public abstract class Handler {
        protected Handler successor;

        public void SetSuccessor(Handler successor) {
            this.successor = successor;
        }

        public abstract void HandleRequest(int request);
    }

    public class ConcreteHandler1 : Handler {
        public override void HandleRequest(int request) {
            if (request >= 0 && request < 10) {
                Console.WriteLine("{0} 处理请求 {1}",this.GetType().Name,request);
            } else if (successor != null) {
                successor.HandleRequest(request);
            }
        }
    }

    public class ConcreteHandler2 : Handler {
        public override void HandleRequest(int request) {
            if (request >= 10 && request < 20) {
                Console.WriteLine("{0} 处理请求 {1}",this.GetType().Name,request);
            } else if (successor != null) {
                successor.HandleRequest(request);
            }
        }
    }

    public class ConcreteHandler3 : Handler {
        public override void HandleRequest(int request) {
            if (request >= 20 && request < 30) {
                Console.WriteLine("{0} 处理请求 {1}",this.GetType().Name,request);
            } else if (successor != null) {
                successor.HandleRequest(request);
            }
        }
    }

}
View Code

[职责链模式(Chain of Responsibility)]使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系
将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止.
当客户提交一个请求时,请求是沿链传递直至有一个ConcreteHandler对象负责处理它
接收者和发送者都没有对方的明确信息,且链中的对象本身也并不知道链的结构.结果是职责链可简化对象的相互链接,
它们仅须要保持一个指向其后继者的引用,而不需保持它全部的候选接受者的引用
随时地增长或修改处理一个请求的结构.加强了给对象指派职责的灵活性

第25章 世界须要和平            [中介者模式]

经过中介者对象,能够将系统的网状结构变成以中介者为中心的星形结构,每一个具体对象再也不经过直接的联系与另外一个对象发生相互做用,
而是经过"中介者"对象与另外一个对象发生相互做用.中介者对象的设计,使得系统的结构不会由于新对象的引入形成大量的修改工做.

using System;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            ConcreteMediator m = new ConcreteMediator();
            ConcreteColleauge1 c1 = new ConcreteColleauge1(m);
            ConcreteColleague2 c2 = new ConcreteColleague2(m);

            m.Colleauge1 = c1;
            m.Colleague2 = c2;
            
            c1.Send("吃过饭了吗?");
            c2.Send("没有呢,你打算请客?");
        }
    }

    public abstract class Mediator {
        public abstract void Send(string message, Colleague colleauge);
    }

    public abstract class Colleague {
        protected Mediator mediator;

        public Colleague(Mediator mediator) {
            this.mediator = mediator;
        }               
    }
    
    

    public class ConcreteMediator : Mediator {
        private ConcreteColleauge1 colleague1;
        private ConcreteColleague2 colleague2;

        public ConcreteColleauge1 Colleauge1 {
            set { colleague1 = value; }
        }

        public ConcreteColleague2 Colleague2 {
            set { colleague2 = value; }
        }

        public override void Send(string message, Colleague colleague) {
            if (colleague == colleague1) {
                colleague2.Notify(message);
            } else {
                colleague1.Notify(message);  
            }
        }
    }
    
    

    public class ConcreteColleauge1 : Colleague {

        public ConcreteColleauge1(Mediator mediator) : base(mediator) {

        }

        public void Send(string message) {
            mediator.Send(message,this);
        }

        public void Notify(string message) {
            Console.WriteLine("同事1获得信息:" + message);
        }
    }

    public class ConcreteColleague2 : Colleague {

        public ConcreteColleague2(Mediator mediator) : base(mediator) {
            
        }

        public void Send(string message) {
            mediator.Send(message,this);
        }
        
        public void Notify(string message) {
            Console.WriteLine("同事2获得信息:" + message);
        }
    }
}
View Code

[中介者模式(Mediator)]用一个中介对象来封装一系列的对象交互.中介者使对象不须要显式地相互引用,从而使其耦合松散,并且能够独立地改变它们之间的交互

中介者模式很容易在系统中应用,也很容易在系统中误用.当系统出现了"多对多"交互复杂的对象群时,不要急于使用中介者模式,而要先反思你的系统在设计上是否是合理

Mediator的出现减小了各个Colleague的耦合,使得能够独立地改变和复用各个Colleague类和Mediator.

因为把对象如何协做进行了抽象,将中介做为一个独立的概念并将其封装在一个对象中,这样关注的对象就从对象各自自己的行为转移到它们之间的交互上来,

也就是站在一个更宏观的角度去看待系统.

第26章 项目多也别傻作         [享元模式]

using System;
using System.Collections.Generic;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            int extrinsicstate = 22;
            
            FlyweightFactory f = new FlyweightFactory();
            
            Flyweight fx = f.GetFlyweight("X");
            fx.Operation(--extrinsicstate);

            Flyweight fy = f.GetFlyweight("Y");
            fy.Operation(--extrinsicstate);

            Flyweight fz = f.GetFlyweight("Z");
            fz.Operation(--extrinsicstate);
            
            UnsharedConcreteFlyweight uf = new UnsharedConcreteFlyweight();
            uf.Operation(--extrinsicstate);
            
        }
    }

    public abstract class Flyweight {
        public abstract void Operation(int extrinsicstate);
    }

    public class ConcreteFlyweight : Flyweight {
        public override void Operation(int extrinsicstate) {
            Console.WriteLine("具体Flyweight:" + extrinsicstate);
        }
    }

    public class UnsharedConcreteFlyweight : Flyweight {
        public override void Operation(int extrinsicstate) {
            Console.WriteLine("不共享的具体Flyweight:" + extrinsicstate);
        }
    }

    public class FlyweightFactory {
        private Dictionary<string,Flyweight> flyweights = new Dictionary<string, Flyweight>();

        public FlyweightFactory() {
            flyweights.Add("X",new ConcreteFlyweight());
            flyweights.Add("Y",new ConcreteFlyweight());
            flyweights.Add("Z",new ConcreteFlyweight());
        }

        public Flyweight GetFlyweight(string key) {
            return flyweights[key];
        }
    }
}
View Code

[享元模式(Flyweight)]运用共享技术有效地支持大量细粒度的对象.
享元模式能够避免大量很是相似的开销.在程序设计中,有时须要生成大量细粒度的类实例来表示数据.
若是能发现这些实例除了几个参数外基本上都是相同的,有时就可以受大幅度地减小须要实例化的类的数量.
若是能把那些参数移到类实例的外面,再方法调用时将它们传递进来,就能够经过共享大幅度地减小单个实例的数目
若是一个应用程序使用了大量的对象,而大量的这些对象形成了很大的存储开销时就应该考虑使用;

还有就是对象的大多数状态能够外部状态,若是删除对象的外部状态,那么能够用相对较少的共享对象取代不少组对象,
此时能够考虑使用享元模式

第27章 其实你不懂老板的心       [解释器模式]

using System;
using System.Collections.Generic;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            Context context = new Context();
            IList<AbstractExpression> list = new List<AbstractExpression>();
            list.Add(new TerminalExpression());
            list.Add(new NonterminalExpression());
            list.Add(new TerminalExpression());
            list.Add(new TerminalExpression());

            foreach (AbstractExpression exp in list) {
                exp.Interpret(context);
            }
        }
    }

    public abstract class AbstractExpression {
        public abstract void Interpret(Context context);
    }

    public class TerminalExpression : AbstractExpression {
        public override void Interpret(Context context) {
            Console.WriteLine("终端解释器");
        }
    }

    public class NonterminalExpression : AbstractExpression {
        public override void Interpret(Context context) {
            Console.WriteLine("非终端解释器");
        }
    }

    public class Context {
        private string input;
        private string output;
        
        
        public string Input {
            get { return input; }
            set { input = value; }
        }

        public string Output {
            get { return output; }
            set { output = value; }
        }
    }
}
View Code

[解释器模式(interpreter)]给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子
若是一种特定类型的问题发生的频率足够高,那么可能就值得将该问题的各个实例表述为一个简单语言的句子.
这样就能够构建一个解释器,该解释器经过解释这些句子来解决该问题.
当有一个语言须要解释执行,而且你可将该语言中的句子表示为一个抽象语法树时,可以使用解释器模式
用了解释器模式,就意味着能够很容易地改变和扩展文法,由于该模式使用类来表示文法规则,你可以使用继承来改变或扩展该文法.
也比较容易实现文法,由于定义抽象语法树中各个节点的类的实现大致相似,这些类都易于直接编写

解释器模式也有不足的,解释器模式为文法中的每一条规则至少定义了一个类,所以包含许多规则的文法可能难以管理和维护.
建议当文法很是复杂时,使用其余的技术如语法分析程序或编译器生成器来处理.

第28章 男人和女人          [访问者模式]

using System;
using System.Collections.Generic;

namespace Test2 {
    class Program {
        static void Main(string[] args) {
            ObjectStructure o = new ObjectStructure();
            o.Attach(new ConcreteElementA());
            o.Attach(new ConcreteElementB());
            
            ConcreteVisitor1 v1 = new ConcreteVisitor1();
            ConcreteVisitor2 v2 = new ConcreteVisitor2();
            o.Accept(v1);
            o.Accept(v2);
        }
    }

    public abstract class Element {
        public abstract void Accept(Visitor visitor);
    }

    public class ConcreteElementA : Element {
        public override void Accept(Visitor visitor) {
            visitor.VisitConcreteElementA(this);
        }

        public void OperationA() {
            
        }
    }

    public class ConcreteElementB : Element {
        public override void Accept(Visitor visitor) {
            visitor.VisitConcreteElementB(this);
        }

        public void OperationB() {
            
        }
    }
    
    public abstract class Visitor {
        public abstract void VisitConcreteElementA(ConcreteElementA concreteElementA);
        public abstract void VisitConcreteElementB(ConcreteElementB concreteElementB);
    }

    public class ConcreteVisitor1 : Visitor {
        public override void VisitConcreteElementA(ConcreteElementA concreteElementA) {
            Console.WriteLine("{0}被{1}访问", concreteElementA.GetType().Name, this.GetType().Name);
        }

        public override void VisitConcreteElementB(ConcreteElementB conreteElementB) {
            Console.WriteLine("{0}被{1}访问", conreteElementB.GetType().Name, this.GetType().Name);
        }
    }
    
    public class ConcreteVisitor2 : Visitor {
        public override void VisitConcreteElementA(ConcreteElementA concreteElementA) {
            Console.WriteLine("{0}被{1}访问", concreteElementA.GetType().Name, this.GetType().Name);
        }

        public override void VisitConcreteElementB(ConcreteElementB conreteElementB) {
            Console.WriteLine("{0}被{1}访问", conreteElementB.GetType().Name, this.GetType().Name);
        }
    }

    public class ObjectStructure {
        private IList<Element> elements = new List<Element>();

        public void Attach(Element element) {
            elements.Add(element);
        }

        public void Detach(Element element) {
            elements.Remove(element);
        }

        public void Accept(Visitor visitor) {
            foreach (Element e in elements) {
                e.Accept(visitor);
            }
        }
    }
}
View Code

[访问者模式(Visitor)]表示一个做用于某对象结构中的各元素的操做.它使你能够在不改变各元素的前提下定义做用于这些元素的新操做

第29章 OOTV杯超级模式大赛      [模式总结]   

相关文章
相关标签/搜索