zno2

7) Bridge Pattern

类别:

 Structural Patterns

问题:

连连看的问题

 

不使用桥接,要写81 个类,使用桥接,只需要18个类

方案:

 

示例:

 

public class BridgePatternDemo {

    public static void main(String[] args) {
        Somebody sb = new Xiaohong(new Banana());
        sb.eat();
        sb = new Liming(new Apple());
        sb.eat();
    }
}

interface Something {
    public String getName();
}

class Apple implements Something {

    public String getName() {
        return "apple";
    }

}

class Banana implements Something {

    public String getName() {
        return "banana";
    }

}

abstract class Somebody {
    protected Something something;

    public Somebody(Something something) {
        this.something = something;
    }

    abstract public void eat();
}

class Xiaohong extends Somebody {

    public Xiaohong(Something something) {
        super(something);
    }

    @Override
    public void eat() {
        System.out.println("Xiaohong eat " + something.getName());
    }

}

class Liming extends Somebody {

    public Liming(Something something) {
        super(something);
    }

    @Override
    public void eat() {
        System.out.println("Liming eat " + something.getName());
    }

}

 

Xiaohong eat banana
Liming eat apple

 

应用:

 

不足:(

 

优化:)

 

posted on 2023-06-06 13:21  zno2  阅读(9)  评论(0编辑  收藏  举报

导航