设计模式学习笔记简述
创建型模式
1.抽象工厂模式(Abstract Factory):提供一个创建一系列或相关依赖对象的接口,而无需指定它们具体的类。
2.建造者模式(Builder):将一个浮躁对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
3.工厂模式(Factory ):定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂模式使一个类的实例化延迟到其子类。
4.原型模式(Prototype):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
5.单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点。
结构型模式
6.适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
7.桥接模式(Bridge):将抽象部分与它的实现部分分离,使它们都可以独立地变化。
8.组合模式(Composite):将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
9.装饰模式(Decorator):动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
10.外观模式(Facade):为子系统中的一组接口提供一个一致的界面,此模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。
11.享元模式(Flyweight):运用共享技术有效地支持大量细粒度的对象。
12.代理模式(Proxy):为其它对象提供一种代理以控制对这个对象的访问。
行为型模式
13.观察者模式:定义了一种一对多的依赖关系,让多个观察者对象同时监听某一个主题对象。这个主题对象在状态发生变化时,会通知所有观察者对象,使他们能够自动更新自己。
14.模板方法模式:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构既可重定义该算法的某些特定步骤。
15.命令模式(Command):将一个请求封装为一个对象,从而使你可用不同的请求对客户进行参数化;对请求排队或记录请求日志,以及支持可撤销的操作。
16.状态模式(State):当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
17.职责链模式(Chain of Responsibility):使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
18.解释器模式(interpreter):给定一个语言,定义它的文法的一种表示,并定义一个解释器,这个解释器使用该表示来解释语言中的句子。
19.中介者模式(Mediator):用一个中介对象来封装一系列对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
20.访问者模式(Visitor):表示一个作用于某对象结构中的各元素的操作。它使你可以在不改变各元素的类的前提下定义作用于这些元素的新操作。
21.策略模式:(Strategy):它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化,不会影响到算法的客户。
22.备忘录模式(Memento):在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。
23.迭代器模式 (Iterator):提供一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示。
Gof设计模式的UML定义:
创建型模式
1.抽象工厂模式(Abstract Factory):
2.建造者模式(Builder):
3.工厂模式(Factory ):
4.原型模式(Prototype):
5.单例模式(Singleton):
结构型模式
6.适配器模式(Adapter):
7.桥接模式(Bridge):
8.组合模式(Composite):
9.装饰模式(Decorator):
10.外观模式(Facade):
11.享元模式(Flyweight):
12.代理模式(Proxy):
行为型模式
13.观察者模式:
14.模板方法模式:
15.命令模式(Command):
17.职责链模式(Chain of Responsibility):
18.解释器模式(interpreter):
19.中介者模式(Mediator):
20.访问者模式(Visitor):
21.策略模式:(Strategy):
22.备忘录模式(Memento):
23.迭代器模式 (Iterator):
Gof设计模式的代码实现:
创建型模式
1.抽象工厂模式(Abstract Factory):
using System;
namespace 抽象工厂模式
{
class Program
{
static void Main(string[] args)
{
AbstractFactory factory1 = new ConcreteFactory1();
Client c1 = new Client(factory1);
c1.Run();
AbstractFactory factory2 = new ConcreteFactory2();
Client c2 = new Client(factory2);
c2.Run();
}
}
abstract class AbstractProductA
{
}
abstract class AbstractProductB
{
public abstract void Interact(AbstractProductA a);
}
class ProductA1 : AbstractProductA
{
}
class ProductA2 : AbstractProductA
{
}
class ProductB1 : AbstractProductB
{
public override void Interact(AbstractProductA a)
{
Console.WriteLine(this.GetType().Name + "intracts with " + a.GetType().Name);
}
}
class ProductB2 : AbstractProductB
{
public override void Interact(AbstractProductA a)
{
Console.WriteLine(this.GetType().Name + "interacts with "+a.GetType().Name);
}
}
abstract class AbstractFactory
{
public abstract AbstractProductA CreateProductA();
public abstract AbstractProductB CreateProductB();
}
class ConcreteFactory1:AbstractFactory
{
public override AbstractProductA CreateProductA()
{
return new ProductA1();
}
public override AbstractProductB CreateProductB()
{
return new ProductB1();
}
}
class ConcreteFactory2 : AbstractFactory
{
public override AbstractProductA CreateProductA()
{
return new ProductA2();
}
public override AbstractProductB CreateProductB()
{
return new ProductB2();
}
}
class Client
{
private AbstractProductA AbstractProductA;
private AbstractProductB AbstractProductB;
public Client(AbstractFactory factory)
{
AbstractProductA = factory.CreateProductA();
AbstractProductB = factory.CreateProductB();
}
public void Run()
{
AbstractProductB.Interact(AbstractProductA);
}
}
}
2.建造者模式(Builder):
using System;
using System.Collections.Generic;
namespace 建造者模式
{
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();
}
}
class Product
{
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);
}
}
}
abstract class Builder
{
public abstract void BuildPartA();
public abstract void BuildPartB();
public abstract Product GetResult();
}
class Director
{
public void Construct(Builder builder)
{
builder.BuildPartA();
builder.BuildPartB();
}
}
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;
}
}
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;
}
}
}
3.工厂模式(Factory ):
using System;
namespace 工厂模式
{
class Program
{
static void Main(string[] args)
{
//基本方式:薛磊风代表大学生学习雷锋
LeiFeng xueleifeng = new Undergraduate();
xueleifeng.BuyRice();
xueleifeng.Sweep();
xueleifeng.Wash();
LeiFeng student1 = new Undergraduate();
student1.BuyRice();
LeiFeng student2 = new Undergraduate();
student2.Sweep();
LeiFeng student3 = new Undergraduate();
student3.Wash();
//简单工厂模式
LeiFeng studengA = SimpleFactory.CreateLeiFeng("学雷锋的大学生");
studengA.BuyRice();
LeiFeng studentB = SimpleFactory.CreateLeiFeng("学雷锋的大学生");
studentB.Sweep();
LeiFeng studentC = SimpleFactory.CreateLeiFeng("学雷锋的大学生");
studentC.Wash();
//工厂方法模式
IFacory factory = new UndergraduateFactory();
LeiFeng student = factory.CreateLeiFeng();
student.BuyRice();
student.Sweep();
student.Wash();
}
}
class LeiFeng
{
public void Sweep()
{
Console.WriteLine("扫地");
}
public void Wash()
{
Console.WriteLine("洗衣");
}
public void BuyRice()
{
Console.WriteLine("买米");
}
}
//学雷锋的大学生
class Undergraduate : LeiFeng
{
}
//社区志愿者
class Volunteer : LeiFeng
{
}
//简单雷锋工厂
class SimpleFactory
{
public static LeiFeng CreateLeiFeng(string type)
{
LeiFeng result = null;
switch (type)
{
case "学雷锋的大学生":
result = new Undergraduate();
break;
case "社区志愿者":
result = new Volunteer();
break;
}
return result;
}
}
//雷锋工厂
interface IFacory
{
LeiFeng CreateLeiFeng();
}
//学雷锋的大学生工厂
class UndergraduateFactory : IFacory
{
public LeiFeng CreateLeiFeng()
{
return new Undergraduate();
}
}
//社区志愿者工厂
class VolunteerFactory : IFacory
{
public LeiFeng CreateLeiFeng()
{
return new Volunteer();
}
}
}
4.原型模式(Prototype):
using System;
namespace 原型模式
{
class Program
{
static void Main(string[] args)
{
ConcreteProtype1 p1 = new ConcreteProtype1("I");
ConcreteProtype1 c1 = (ConcreteProtype1)p1.Clone();
Console.WriteLine("Cloned:{0}",c1.Id);
ConcreteProtype2 p2 = new ConcreteProtype2("II");
ConcreteProtype2 c2 = (ConcreteProtype2)p2.Clone();
Console.WriteLine("Cloned:{0}",p2.Id);
}
}
abstract class Prototype
{
private string id;
public Prototype(string id)
{
this.id = id;
}
public string Id
{
get
{
return id;
}
}
public abstract Prototype Clone();
}
class ConcreteProtype1 : Prototype
{
public ConcreteProtype1(string id):base(id)
{
}
public override Prototype Clone()
{
return (Prototype)this.MemberwiseClone();
}
}
class ConcreteProtype2 : Prototype
{
public ConcreteProtype2(string id):base(id)
{
}
public override Prototype Clone()
{
return (Prototype)this.MemberwiseClone();
}
}
}
5.单例模式(Singleton):
using System;
namespace 单例模式
{
class Program
{
static void Main(string[] args)
{
Singleton s1 = Singleton.GetInstance();
Singleton s2 = Singleton.GetInstance();
if (s1== s2)
{
Console.WriteLine("Object are the same instance");
}
}
}
class Singleton
{
private static Singleton instance;
private static readonly object syncRoot = new object();
private Singleton()
{
}
public static Singleton GetInstance()
{
if (instance == null)
{
lock (syncRoot)
{
if (instance ==null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
结构型模式
6.适配器模式(Adapter):
using System;
namespace 适配器模式
{
class Program
{
static void Main(string[] args)
{
Target target = new Adapter();
target.Request();
}
}
class Target
{
public virtual void Request()
{
Console.WriteLine("普通请求");
}
}
class Adaptee
{
public void SpecificRequest()
{
Console.WriteLine("特殊请求");
}
}
class Adapter : Target
{
private Adaptee adaptee = new Adaptee();
public override void Request()
{
adaptee.SpecificRequest();
}
}
}
7.桥接模式(Bridge):
using System;
namespace 桥接模式
{
class Program
{
static void Main(string[] args)
{
Abstraction ab = new RefinedAbstraction();
ab.SetImplementor(new ConcreteImplementorA());
ab.Operation();
ab.SetImplementor(new ConcreteImplementorB());
ab.Operation();
}
}
abstract class Implementor
{
public abstract void Operation();
}
class Abstraction
{
protected Implementor implementor;
public void SetImplementor(Implementor implementor)
{
this.implementor = implementor;
}
public virtual void Operation()
{
implementor.Operation();
}
}
class RefinedAbstraction : Abstraction
{
public override void Operation()
{
implementor.Operation();
}
}
class ConcreteImplementorA : Implementor
{
public override void Operation()
{
Console.WriteLine("具体实现A的方法执行");
}
}
class ConcreteImplementorB : Implementor
{
public override void Operation()
{
Console.WriteLine("具体实现B的方法执行");
}
}
}
8.组合模式(Composite):
using System;
using System.Collections.Generic;
namespace 组合模式
{
class Program
{
static void Main(string[] args)
{
Composite root = new Composite("root");
root.Add(new Leaf("Leaf A"));
root.Add(new Leaf("Leaf B"));
Component comp = new Composite("Composite X");
comp.Add(new Leaf("Leaf XA"));
comp.Add(new Leaf("Leaf XB"));
root.Add(comp);
Composite comp2 = new Composite("Composite XY");
comp2.Add(new Leaf("Leaf XYA"));
comp2.Add(new Leaf("Leaf XYB"));
comp.Add(comp2);
root.Add(new Leaf("Leaf C"));
Leaf leaf = new Leaf("Leaf D");
root.Add(leaf);
root.Remove(leaf);
root.Display(1);
}
}
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);
}
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);
}
}
}
class Leaf : Component
{
public Leaf(string name)
: base(name)
{ }
public override void Add(Component c)
{
Console.WriteLine("Cannot add to a leaf");
}
public override void Remove(Component c)
{
Console.WriteLine("Cannot remove from a leaf");
}
public override void Display(int depth)
{
Console.WriteLine(new String('-', depth) + name);
}
}
}
9.装饰模式(Decorator):
using System;
namespace 装饰模式
{
class Program
{
static void Main(string[] args)
{
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcretedDecoratorB d2 = new ConcretedDecoratorB();
d1.SetComponent(c);
d2.SetComponent(d1);
d2.Operation();
}
}
abstract class Component
{
public abstract void Operation();
}
class ConcreteComponent : Component
{
public override void Operation()
{
Console.WriteLine("具体对象的操作");
}
}
abstract class Decorator : Component
{
protected Component component;
public void SetComponent(Component component)
{
this.component = component;
}
public override void Operation()
{
if (component !=null)
{
component.Operation();
}
}
}
class ConcreteDecoratorA : Decorator
{
private string addedState;
public override void Operation()
{
base.Operation();
addedState = "New State";
Console.WriteLine("具体装饰对象A的操作");
}
}
class ConcretedDecoratorB : Decorator
{
private void AddedBehavior()
{
}
public override void Operation()
{
base.Operation();
AddedBehavior();
Console.WriteLine("具体装饰对象B的操作");
}
}
}
10.外观模式(Facade):
using System;
namespace 外观模式
{
class Program
{
static void Main(string[] args)
{
Facade facde = new Facade();
facde.MethodA();
facde.MethodB();
}
}
class SubSystemOne
{
public void MethodOne()
{
Console.WriteLine("子系统方法一");
}
}
class SubSystemTwo
{
public void MethodTwo()
{
Console.WriteLine("子系统方法二");
}
}
class SubSystemThree
{
public void MethodThree()
{
Console.WriteLine("子系统方法三");
}
}
class SubSystemFour
{
public void MethodFour()
{
Console.WriteLine("子系统方法四");
}
}
class Facade
{
SubSystemOne one;
SubSystemTwo two;
SubSystemThree three;
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();
}
}
}
11.享元模式(Flyweight):
using System;
using System.Collections;
namespace 享元模式
{
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);
Console.Read();
}
}
class FlyweightFactory
{
private Hashtable flyweights = new Hashtable();
public FlyweightFactory()
{
flyweights.Add("X", new ConcreteFlyweight());
flyweights.Add("Y", new ConcreteFlyweight());
flyweights.Add("Z", new ConcreteFlyweight());
}
public Flyweight GetFlyweight(string key)
{
return ((Flyweight)flyweights[key]);
}
}
abstract class Flyweight
{
public abstract void Operation(int extrinsicstate);
}
class ConcreteFlyweight : Flyweight
{
public override void Operation(int extrinsicstate)
{
Console.WriteLine("具体Flyweight:" + extrinsicstate);
}
}
class UnsharedConcreteFlyweight : Flyweight
{
public override void Operation(int extrinsicstate)
{
Console.WriteLine("不共享的具体Flyweight:" + extrinsicstate);
}
}
}
12.代理模式(Proxy):
using System;
namespace 代理模式
{
class Program
{
static void Main(string[] args)
{
Proxy proxy = new Proxy();
proxy.Request();
}
}
abstract class Subject
{
public abstract void Request();
}
class RealSubject : Subject
{
public override void Request()
{
Console.WriteLine("真实的请求");
}
}
class Proxy : Subject
{
RealSubject realSubject;
public override void Request()
{
if (realSubject == null)
{
realSubject = new RealSubject();
}
realSubject.Request();
}
}
}
行为型模式
13.观察者模式:
using System;
using System.Collections.Generic;
namespace 观察者模式
{
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 = "ABC";
s.Notify();
}
}
abstract class Observer
{
public abstract void Update();
}
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();
}
}
}
//具体通知者
class ConcreteSubject : Subject
{
//具体通知者状态
public string SubjectState
{
get;
set;
}
}
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; }
}
}
}
14.模板方法模式:
using System;
namespace 模板方法模式
{
class Program
{
static void Main(string[] args)
{
AbstractClass c;
c = new ConcreteClassA();
c.TemplateMethod();
c = new ConcreteClassB();
c.TemplateMethod();
}
}
abstract class AbstractClass
{
public abstract void PrimitiveOperation1();
public abstract void PrimitiveOperation2();
public void TemplateMethod()
{
PrimitiveOperation1();
PrimitiveOperation2();
Console.WriteLine("");
}
}
class ConcreteClassA : AbstractClass
{
public override void PrimitiveOperation1()
{
Console.WriteLine("具体类A方法1实现");
}
public override void PrimitiveOperation2()
{
Console.WriteLine("具体类A方法2实现");
}
}
class ConcreteClassB : AbstractClass
{
public override void PrimitiveOperation1()
{
Console.WriteLine("具体类B方法1实现");
}
public override void PrimitiveOperation2()
{
Console.WriteLine("具体类B方法2实现");
}
}
}
15.命令模式(Command):
using System;
namespace 命令模式
{
class Program
{
static void Main(string[] args)
{
Receiver r = new Receiver();
Command c = new ConcreteCommand(r);
Invoker i = new Invoker();
i.SetCommand(c);
i.ExecuteCommand();
}
}
class Receiver
{
public void Action()
{
Console.WriteLine("执行请求!");
}
}
abstract class Command
{
protected Receiver receiver;
public Command(Receiver receiver)
{
this.receiver = receiver;
}
abstract public void Execute();
}
class ConcreteCommand : Command
{
public ConcreteCommand(Receiver receiver)
: base(receiver)
{ }
public override void Execute()
{
receiver.Action();
}
}
class Invoker
{
private Command command;
public void SetCommand(Command command)
{
this.command = command;
}
public void ExecuteCommand()
{
command.Execute();
}
}
}
17.职责链模式(Chain of Responsibility):
18.解释器模式(interpreter):
19.中介者模式(Mediator):
20.访问者模式(Visitor):
21.策略模式:(Strategy):
22.备忘录模式(Memento):
23.迭代器模式 (Iterator):