设计模式(2)结构型模式

结构型模式

桥接模式

将抽象和实现耦合,使得两者可以独立的变化。

interface Implementor{

    void doSomething();
    void doAnything();
}

class ConcreteImplementor1 implements Implementor{

    public void doSomething(){
        //具体业务处理
    }

    public void doAnything(){
        //具体业务处理
    }
}

abstract class Abstraction{

    private Implementor imp;

    public Abstraction(Implementor _imp){
        imp = _imp;
    }

    //自身的行为和属性
    public void request(){
        imp.doSomething();
    }

    public Implementor getImp(){
        return imp;
    }
}

class RefinedAbstraction extends Abstraction{

    public RefinedAbstraction(Implementor _imp){
        super(_imp);
    }

    @Override
    public void request(){
        super.request();
        super.getImp().doAnything();
    }
}

class Client{

    public static void main(String[] args){
        //定义一个实现化角色
        Implementor imp = new ConcreteImplementor1();
        //定义一个抽象化角色
        Abstraction abs = new RefinedAbstraction(imp);
        abs.request();
    }
}

组合模式

文件系统由文件和目录组成,每个文件里装有内容,而每个目录的内容可以有文件和目录,目录就相当于是由单个对象或组合对象组合而成,如果你想要描述的是这样的数据结构,那么你就可以使用组合模式。

abstract class Component {

    public abstract void operation();

    public void add(Component c) {
	    throw new UnsupportedOperationException();
    }

    public void remove(Component c) {
	    throw new UnsupportedOperationException();
    }

    public Component getChild(int i) {
	    throw new UnsupportedOperationException();
    }
}

class ConcreteComponent1 extends Component {

    public void operation() {
	    System.out.println("operation of concrete component 1 ");
    }
}

class ConcreteComponent2 extends Component {

    public void operation() {
	    System.out.println("operation of concrete component 2 ");
    }
}

class ConcreteComponent3 extends Component {

    public void operation() {
	    System.out.println("operation of concrete component 3 ");
    }
}

class Composite extends Component {

    private ArrayList<Component> children;

    public Composite() {
	    children = new ArrayList<Component>();
    }

    public void operation() {
        for(Component child: children) {
            child.operation();
        }
    }

    public void add(Component c) {
	    children.add(c);
    }

    public void remove(Component c) {
	    children.remove(c);
    }

    public Component getChild(int i) {
	    return children.get(i);
    }
}

public class Client {

    public static void main(String[] args) {

        Component c1 = new ConcreteComponent1();
        Component c2 = new ConcreteComponent2();
        Component c3 = new ConcreteComponent3();

        Component c = new Composite();
        c.add(c1);
        c.add(c2);
        c.add(c3);
        c.operation();

        c.remove(c2);
        c.operation();
    }
}

享元模式

享元,就是共享元素的意思。

https://zhuanlan.zhihu.com/p/53087983

行为型模式

策略模式

模板方法模式

观察者模式