略读设计模式(二)

适配器模式:

class Adapter extends Target {
    private Adaptee adaptee;
    public Adapter(Adaptee adaptee) {
        this.adaptee=adaptee;
    }
    public void request() {
        adaptee.specificRequest();
    }
}

桥接模式:

interface Implementor {
    public void operationImpl();
}

abstract    class Abstraction {
    protected Implementor impl;
    public void setImpl(Implementor impl) {
        this.impl=impl;
    }
    public abstract void     operation();
}

class RefinedAbstraction     extends Abstraction{
    public void operation() {
        impl.operationImpl();
    }
}

组合模式:

class ImageFile {
    private String name;
    public ImageFile(String name) {
        this.name = name;
    }
    public void killVirus() {
        System.out.println("----对图像文件'" + name + "'进行杀毒");
    }
}

class TextFile {
    private String name;
    public TextFile(String name) {
        this.name = name;
    }
    public void killVirus() {
        System.out.println("----对文本文件'" + name + "'进行杀毒");
    }
}

class Folder {
    private String name;
    private ArrayList<Folder> folderList = new ArrayList<Folder>();
    private ArrayList<ImageFile>    imageList = new ArrayList<ImageFile>();
    private ArrayList<TextFile> textList = new ArrayList<TextFile>();
    public Folder(String    name) {
        this.name = name;
    }

    public void addFolder(Folder    f) {
        folderList.add(f);
    }
    public void addFolder(Folder    f) {
        folderList.add(f);
    }

    public void addImageFile(ImageFile image) {
        imageList.add(image);
    }

    public void addTextFile(TextFile text) {
        textList.add(text);
    }

    public void killVirus() {
        System.out.println("****对文件夹'" + name + "'进行杀毒");
        for(Object obj :     folderList) {
            ((Folder)obj).killVirus();
        }

        for(Object obj :     imageList) {
            ((ImageFile)obj).killVirus();
        }

        for(Object obj :     textList) {
            ((TextFile)obj).killVirus();
        }
    }
}

装饰模式:

class Decorator implements Component {
    private Component component;    
    public Decorator(Component component) {
        this.component=component;
    }
    public void operation() {
        component.operation();
    }
}

class ConcreteDecorator extends Decorator {
    public ConcreteDecorator(Component component) {
        super(component);
    }
    public void operation() {
        super.operation();
        addedBehavior();    
    }
    public void addedBehavior() {
        ......
    }
}

书籍地址:https://gof.quanke.name/

一个有关“略读设计模式(二)”的想法

  1. 关于建造者模式,我到现在没看懂。等懂了,在附上代码。

发表评论

This site uses Akismet to reduce spam. Learn how your comment data is processed.