设计模式笔记

这两天快速将设计模式学习了一遍,总结了如下几下:

  1. Builder模式
    Builder模式seperate construction of a complex object from its representation so that the same construction process can create different representation. 将一系列的构造过程封装,在每一步的构造中引入不同的参数,从而使相同的构造步骤产生不同的结果。
  2. Adapter模式
    Adapter模式Provide an interface for creating families of related or independent objects without specifying their concrete classes. Adapter模式的作用就是接口转换,在不改变原接口的情况下,能够使已有功能复用。


class Adapter extends Shape{    
    private Ellipse ellipseObj = new Ellipse();
    @Override   
    public void Draw(){     
        //复用已有的DrawEllipse接口,而不用新建一个类           
        ellipseObj.DrawEllipse();   
    }
  1. Bridge模式
    Bridge模式Decouple an abstraction from its implementation so that the two can vary independently. 将定义与实现解耦,从而使两者能够独立的变化。



    Bridge模式中,最关键的步骤是在Abstraction中定义一个AbstractionImpl的对象用于表示实现,当RefinedAbstraction中需要哪种实现,就SetImpl哪种实现。

public static void main(String[] args){
    RefineAbstract abstraction = new RefineAbstract();
    Implementation implA = new ImplementationA();
    Implementation implB = new ImplementationB();          
    abstraction.setImpl(implA); 
    abstraction.Operation();
}
  1. Decorate模式
    Decorate模式 Attach additional responsibilities to an object dynamically keeping the same interface. Decorateprovide a flexible alternative to subclass for extending functionally. 动态地给一个对象添加一些额外的职责。就增加的功能来说,装饰模式相比生成子类更为灵活。该种模式适用于给已有类添加新的功能,但不知道新的功能的实现顺序。



    重要的是, 1、Decorate继承了Component,从而使用基类类型与接口,也能实现Decorate功能!2、构造函数使用了Componet对象,从而使一个ConcreteDecorator能够初始化另外一个ConcreteDecorate,实现了功能顺序的任意调换!

public class MyFileSys {    
    public static void main(String[] args) {        
        FileSys fileSys = new StandardFileSys();//可以随意调换Rar与Encrypt的顺序  
        FileSys rarFileSys = new RarFileSys(fileSys);
        FileSys encryptFileSys = new EncryptFileSys(rarFileSys);//使用的是基类类型与定义的指针,实现的是Decorate类的功能。
        encryptFileSys.Operation(); 
    }
}
abstract class FileSys{
    abstract public void Operation();
}
class StandardFileSys extends FileSys {
    @Override
    public void Operation(){
        System.out.println("New a FileSys");
    }
}
//Decorate类继承Component类,从而使用基类类型与定义好的接口,就能实现Decorate类的功能。
class DecorateFileSys extends FileSys{  
    //使用组合类型
    protected FileSys fileSys;
    public DecorateFileSys(FileSys fileSys) {
        this.fileSys = fileSys;
    }
    @Override
    public void Operation(){
        fileSys.Operation();
    }
}
class EncryptFileSys extends DecorateFileSys{
    public EncryptFileSys(FileSys fileSys) {
        super(fileSys);
    }
    @Override   
    public void Operation(){
        super.Operation();
        Encrypt();
    }
}
  1. Composite模式
    Composite模式Compose objectsinto tree structure to represent part-whole hierarchies. Composite lets clientstreat individual objects and compositions of object uniformly.将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。
    想想文件夹
  2. Facede模式
    Façade模式 Provide a unified interface to a set of interface in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use. 要求一个子系统的外部与其内部的通信必须通过一个统一的对象进行。门面模式提供了一个高层次的接口,使得子系统更容易使用。
    Façade模式面对的往往是多个类或其他程序单元,通过重新组合各类及程序单元,对外提供统一的接口/界面。


public class CarFacade{
    public static void main(String[] args){
        int[] flags = new int[]{1,2,3,4};
        Facade carFacade = new Facade(flags);
        carFacade.Run();
        carFacade.Stop();
    }
}
class Facade{
    protected Wheel[] wheel = new Wheel[4];
    protected Body body;
    public Facade(int[] flags) {
        for(int i = 0; i<4; i++){
            wheel[i] = new Wheel(flags[i]);
        }
        body = new Body();
    }       
    public void Stop () {
        for(int i = 0; i<4; i++){
              wheel[i].Stop();
        }
        body.Stop();
    }
    public void Run () {
        for(int i = 0; i<4; i++){
            wheel[i].Run();
        }
        body.Run();
    }
}
  1. Template模式
    Template模式Define the skeleton of an algorithm in an operation, deferring some steps to subclass. Template Method lets subclass redefine certain steps of an algorithm without changing the algorithm’ structure. 定义一个操作中的算法框架,将一些步骤延迟到子类。使得子类算法可以不改变一个算法的结构即可以重定义该算法的某些特定步骤。
    Template模式通过继承,将通用的算法架构抽象成接口,而将算法实现延迟到了子类实现。从而实现了不同的子类,其算法框架是一致的,但算法方法不一致。
    DIP(依赖倒置), 由父类定义接口,控制权在父类。将具体实现和抽象接口之间解耦。
abstract class Template {
    public void Operation(){
        ExecuteStep1();
        ExecuteStep2();
    }
    abstract void ExecuteStep1();
    abstract void ExecuteStep2();
}
class ConcreteTemplate1 extends Template{
    void ExecuteStep1(){
        System.out.println("Execute Step1 of ConcreteTemplate1");
    }
    void ExecuteStep2(){
        System.out.println("Execute Step2 of ConcreteTemplate1");
    }
}
public class Client{
    public static void main(String[] args){
        Template template1 = new ConcreteTemplate1();
        template1.Operation();
    }
}
  1. Strategy模式
    Strategy模式 Define a family of algorithms, en capsulate each one, and make them interchangeable. 定义一组算法,将每个算法都封装起来,使得他们之间可以互换。
    通过组合,Context中存放算法类对象Strategy,不同的Strategy对象,实现不同的算法。
public class Client {
    public static void main(String[] args){
        Stratery strateryA = new StrageryA();
        ContextExample curContext = new ContextExample(strateryA);
        curContext.Execute();
    }
}
abstract class Stratery{
    abstract void Operation();
}
class StrageryA extends Stratery{
    @Override
    void Operation(){
        System.out.println("Execute StrageryA");
    }
}
class ContextExample{
    Stratery stragery;
    public ContextExample(Stratery stratery){
        this.stragery = stratery;
    }
    public void Execute(){
        stragery.Operation();
    }
}

9.Command模式
Command模式 Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.将一个请求封装成一个对象,从而让你使用不同的请求把客户端参数化,对请求排队或者记录请求日志,可以提供命令的撤销和恢复功能。
调用者,命令,执行者之间的解耦,将命令封装成类,许多系统的消息发送,异步的,就是采用此模式。


public class Client {
    public static void main(String[] args){
        CommandReceiver commandReceiver = new CommandReceiver();
        Command command = new ConcreteCommand(commandReceiver);
        Invoke invoke = new Invoke();
        invoke.setCommand(command);
        invoke.executeCommand();
    }
}
//将命令封装成类
abstract class Command{
    protected CommandReceiver commondReceiver;
    public Command(CommandReceiver commandReceiver){
        this.commondReceiver = commandReceiver;
    }
    abstract void execute();
}
class ConcreteCommand extends Command{
    public ConcreteCommand(CommandReceiver commandReceiver){
        super(commandReceiver);
    }
    void execute(){
        this.commondReceiver.execute();
    }
}
//命令的执行者
class CommandReceiver{
    public void execute(){
        System.out.println("execute commond");
    }
}
//命令的调用者
class Invoke{
    protected Command command;
    public void setCommand(Command command){
        this.command = command;
    }
    public void executeCommand(){
        this.command.execute();
    }
}
  1. Observer模式
    Observer模式Defined a one-to-many dependency between objects so that when one object changes state,all its dependents are notified and update automatically. 定义对象间一种一对多的依赖关系,使得每当一个对象改变状态,则所有依赖于它的对象都会得到通知并被自动更新。


public class Client {
    public static void main(String[] args){
        Subject subject = new ConcreteSubject();//新建观察者时,就把自己加到了被观察者的队列中
        ObserverA observerA = new ObserverA(subject);
        ObserverB observerB = new ObserverB(subject);//被观察者每更新一次状态,观察者就都收到通知        
        subject.setState(Subject.OPEN_STATE);
        System.out.println();
        subject.setState(Subject.CLOSED_STATE);
        observerA.detach();
        observerB.detach();
    }
}
abstract class Subject{
    static final int OPEN_STATE = 0;
    static final int CLOSED_STATE = 1;
    protected int state = CLOSED_STATE;
    protected Vector<Observer> observers = new Vector<Observer>();
    abstract void attach(Observer observer);
    abstract void detach(Observer observer);
    abstract void notify();
    void setState(int state){
        this.state = state;
        notify();
    }       
    int getState(){
        return state;
    }
}
class ConcreteSubject extends Subject{
    void attach(Observer observer){
        observers.add(observer);
    }       
    void detach(Observer observer){
        observers.removeElement(observer);
    }
    void notify(){
        Iterator<Observer> iterator;
        for(iterator = observers.iterator(); iterator.hasNext();){
            Observer observer = (Observer)iterator.next();
            observer.update();
        }
    }
}
abstract class Observer{
    protected Subject subject;
    public Observer(Subject subject){
        this.subject = subject;
        this.subject.attach(this);
    }
    protected void detach() {
        if (subject!=null) {
            this.subject.detach(this);
        }
    }
    abstract void update();
}
class ObserverA extends Observer{
    public ObserverA(Subject subject) {
        super(subject);
    }
    void update(){
        int state = subject.getState();
        String outpString = "Subject's state is "+Integer.toString(state)+" from ObserverA";
        System.out.println(outpString);
    }
}
class ObserverB extends Observer{
    public ObserverB(Subject subject) {
        super(subject);
    }
    void update(){
         int state = subject.getState();
        String outpString = "Subject's state is "+Integer.toString(state)+" from ObserverB";
        System.out.println(outpString);
    }
}
  1. State模式
    State模式Allow an object to alter its behavior when its internal state changes. The object will appear to change its class. 当一个对象在状态改变时允许其改变行为,这个对象看起来像改变了其类。


public class Client {
    public static void main(String[] args) {
        Fire fire = new Fire();
        fire.TurnOffFire();
        fire.TurnUpFire();
        fire.TurnUpFire();
        fire.TurnOffFire();
        fire.TurnUpFire();
        fire.TurnUpFire();
        fire.TurnOffFire();
        fire.TurnUpFire();
    }
}
abstract class FireState {
    abstract public void TurnUpFire(Fire fire);
    abstract public void TurnOffFire(Fire fire);
}
class Fire{
    FireState fireState;
    public Fire() {
        fireState = new OffState();
    }       
    public void SetFireState(FireState fireState){
        this.fireState = fireState;
    }
    public FireState GetFireState(){
        return fireState;
    }
    public void TurnUpFire(){
        fireState.TurnUpFire(this);
    }
    public void TurnOffFire(){
        fireState.TurnOffFire(this);
    }
}
class OffState extends FireState {
    public void TurnUpFire(Fire fire) {
        fire.SetFireState(new LowState());
        System.out.println("已调至小火");
    }  
    public void TurnOffFire(Fire fire) {
        System.out.println("火未打着");
    }
}
class LowState extends FireState {
    public void TurnUpFire(Fire fire) {
        fire.SetFireState(new MediumState());
        System.out.println("已调至中火");
        }
    public void TurnOffFire(Fire fire) {
        fire.SetFireState(new OffState());
        System.out.println("火已熄灭");
    }
}
class MediumState extends FireState {
    public void TurnUpFire(Fire fire) {
        fire.SetFireState(new HighState());
        System.out.println("已调至大火");
    }
    public void TurnOffFire(Fire fire) {
        fire.SetFireState(new LowState());
        System.out.println("已调至小火");
    }
}
class HighState extends FireState {
    public void TurnUpFire(Fire fire) {
        System.out.println("已是最大火");
    }
    public void TurnOffFire(Fire fire) {
        fire.SetFireState(new MediumState());
        System.out.println("已调至中火");
    }
}
  1. Visitor模式
    Visitor模式Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. 封装一些作用于某种数据结构中的各种元素,它可以在不改变数据结构的前提下定义作用于这些元素的新的操作。
    Visitor双重分派,调用者的动态解析


public class Client {
    public static void main(String[] args){
        Visitor visitor = new XinAnJiang();
        Disaster disaster = new SnowDisaster();
        disaster.accept(visitor);
    }
}
abstract class Visitor{
    abstract public void visit(Disaster disaster);
}
class XinAnJiang extends Visitor{
    @Override   
    public void visit(Disaster disaster) {
        String outString = "XinAnJiang Model Work on "+ disaster.toString();
        System.out.println(outString);
    }
}
class ShuoMoXing extends Visitor{
    @Override
    public void visit(Disaster disaster) {
        String outString = "ShuoMoXing Model Work on "+ disaster.toString();
        System.out.println(outString);
    }
}
abstract class Disaster{
    protected String name;
    public void accept(Visitor visitor){
        visitor.visit(this);
    }
}
class SnowDisaster extends Disaster{
    @Override
    public String toString() {
        return "SnowDisster";
    }
}
class FireDisaster extends Disaster{
    @Override
    public String toString(){
        return "FireDisaster";
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,734评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,931评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,133评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,532评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,585评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,462评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,262评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,153评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,587评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,792评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,919评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,635评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,237评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,855评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,983评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,048评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,864评论 2 354

推荐阅读更多精彩内容