回顾23种设计模式(二)——结构型模式

代理,适配器,装饰器,享元,组合,门面,桥接

代理模式

(这里只是简单说下静态代理,JDK动态代理和CGLIB动态代理这里略)
定义:由于某些原因需要给某对象提供一个代理以控制对该对象的访问

//主题接口
public interface Subject {
    void request();
}
//真实主题实现类
public class RealSubject implements Subject{
    public void request() {
        System.out.println("real subject");
    }
}
//代理类
public class Proxy implements Subject{
    private RealSubject realSubject;
    public void request() {
        if (realSubject == null) {
            realSubject = new RealSubject();
        }
        preRequest();
        realSubject.request();
        postRequest();
    }
    private void postRequest() {
        System.out.println("before subject ...");
    }
    private void preRequest() {
        System.out.println("after subject ...");
    }
}

Main方法及输出结果:

    public static void main(String[] args) {
        Proxy proxy = new Proxy();
        proxy.request();
    }
after subject ...
real subject
before subject ...

适配器(Adaptee)模式

定义:将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类能一起工作
优点
1.客户端通过适配器可以透明地调用目标接口。
2.复用了现存的类,程序员不需要修改原有代码而重用现有的适配者类。
3.将目标类和适配者类解耦,解决了目标类和适配者类接口不一致的问题。
缺点
1.对类适配器来说,更换适配器的实现过程比较复杂。
例子:各种adapter都是

对象适配器.gif

//组合方式实现适配器模式:
//即对象适配器
//三相接口
public interface Three {
     void chargedByThree();
}
//二相充电器
public class Two {
    public void chargedByTwo(){
        System.out.println("使用二相插座供电");
    }
}
//二相充电器转三相
public class Adapter implements Three{
    private Two two;
    public Adapter(Two two) {
        this.two = two;
    }
    @Override
    public void chargedByThree() {
        System.out.println("二相转三相 适配器处理中...");
        two.chargedByTwo();
    }
}
//笔记本主类充电
public class Client {
    private Three three;
    public Client(Three three){
        this.three = three;
    }
    public void charged(){
        three.chargedByThree();
    }
}

Main函数及输出结果:

 public static void main(String[] args) {
        Two two = new Two();
        Three three = new Adapter(two);
        Client client = new Client(three);
        client.charged();
    }
二相转三相 适配器处理中...
使用二项插座供电
类适配器.gif
//继承方式实现适配器模式:
//及类适配器
//继承类并实现接口
public class AdapterExtends extends Two implements Three{
    @Override
    public void chargedByThree() {
        System.out.println("二相转三相 继承适配器处理中...");
        this.chargedByTwo();
    }
}

Main函数及输出结果:

public static void main(String[] args) {
        Two two = new Two();
        Three three = new AdapterExtends();
        Client client = new Client(three);
        client.charged();
    }
二相转三相 继承适配器处理中...
使用二项插座供电

桥接模式

定义:将抽象与实现分离,使它们可以独立变化
使用场景:JDBC就是使用的该模式。
mysql的driver和oracle的driver,都实现了Driver接口,生成了DriverInfo类,通过DriverManager能获取对应的connection,springboot默认的连接池就是HikariCP 使用threadlocal+CopyOnWriteArrayList,HikariCP 是一个“零开销”的生产就绪 JDBC 连接池。快速、简单、可靠。大约 130Kb 的库非常轻巧。

//基础接口
public interface Base {
    void operate();
}
//基础接口实现
public class BaseImpl implements Base{
    public void operate() {
        System.out.println("Base operate ...");
    }
}
//扩展抽象类
public abstract class AbstractExtra {
    protected Base base;
    public AbstractExtra(Base base) {
        this.base = base;
    }
    public abstract void extraOperate();
}
//扩展实现类
public class Extra extends AbstractExtra{
    public Extra(Base base) {
        super(base);
    }
    public void extraOperate(){
        System.out.println("Extra extraOperate ...");
        base.operate();
    }
}

Main方法及测试类

    public static void main(String[] args) {
        Base base = new BaseImpl();
        AbstractExtra extra = new Extra(base);
        extra.extraOperate();
    }
Extra extraOperate ...
Base operate ...

装饰(decorator)模式

定义:指在不改变现有对象结构的情况下,动态地给该对象增加一些职责(即增加其额外功能)
优点
1.采用装饰模式扩展对象的功能比采用继承方式更加灵活。
2.可以设计出多个不同的具体装饰类,创造出多个不同行为的组合。
缺点
1.装饰模式增加了许多子类,如果过度使用会使程序变得很复杂

装饰模式.gif

//component通用接口
public interface Component {
    void operation();
}
//接口的实现类
public class CurrentComponent implements Component{
    public CurrentComponent() {
        System.out.println("创建组件");
    }
    public void operation() {
        System.out.println("组件的通用操作...");
    }
}
//装饰模式的抽象类
public abstract class Decorator implements Component{
    private Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    abstract void incrementFunction();

    public void operation() {
        component.operation();
    }
}
//装饰模式的具体实现
public class IncrementAComponent extends Decorator{
    public IncrementAComponent(Component component) {
        super(component);
    }

    void incrementFunction() {
        System.out.println("装饰器A的附加操作...");
    }
}

Main函数及输出结果:

    public static void main(String[] args) {
        Component current = new CurrentComponent();
        current.operation();
        System.out.println("----装饰过后------");
        Component incrementA = new IncrementAComponent(current);
        incrementA.operation();
        ((IncrementAComponent) incrementA).incrementFunction();
    }
创建组件
组件的通用操作...
----装饰过后------
组件的通用操作...
装饰器A的附加操作...

外观模式

外观(Facade)模式的结构比较简单,主要是定义了一个高层接口。它包含了对各个子系统的引用,客户端可以通过它访问各个子系统的功能。现在来分析其基本结构和实现方法。

//外观类
public class Facade {
    private SubSystem1 system1 = new SubSystem1();
    private SubSystem2 system2 = new SubSystem2();
    public void method(){
        system1.method();
        system2.method();
    }
}
//子系统1
public class SubSystem1 {
    public void method(){
        System.out.println("SubSystem1 method ...");
    }
}
//子系统2
public class SubSystem1 {
    public void method(){
        System.out.println("SubSystem2 method ...");
    }
}

Main方法及输出结果:

    public static void main(String[] args) {
        Facade facade = new Facade();
        facade.method();
    }
SubSystem1 method ...
SubSystem2 method ...

享元模式

运用共享技术来有効地支持大量细粒度对象的复用。它通过共享已经存在的又橡来大幅度减少需要创建的对象数量、避免大量相似类的开销,从而提高系统资源的利用率。
字符串常量池
自动装箱 -128-127

//非享元对象
public class UnFlyweight {
    private String info;
    public UnFlyweight(String info) {
        this.info = info;
    }
    public String getInfo() {
        return info;
    }
    public void setInfo(String info) {
        this.info = info;
    }
}
//享元接口
public interface Flyweight {
    void operation(UnFlyweight unFlyweight);
}
//享元接口的具体实现
public class ConcreteFlyweight implements Flyweight{
    private String key;
    public ConcreteFlyweight(String key) {
        this.key = key;
        System.out.println("ConcreteFlyweight create " + key);
    }
    @Override
    public void operation(UnFlyweight unFlyweight) {
        System.out.print("ConcreteFlyweight key is "+key);
        System.out.println(". ConcreteFlyweight operation with unFlyweight["+unFlyweight.getInfo()+"]");

    }
}
//享元工厂
public class FlyweightFactory {
    private HashMap<String, Flyweight> flyweights=new HashMap<>();
    public Flyweight getFlyweight(String key) {
        Flyweight flyweight = flyweights.get(key);
        if(flyweight!=null) {
            System.out.println("Flyweight key "+key+" is already exist.");
        } else {
            flyweight=new ConcreteFlyweight(key);
            flyweights.put(key, flyweight);
        }
        return flyweight;
    }
}

Main方法及输出结果:

    public static void main(String[] args) {
        FlyweightFactory factory = new FlyweightFactory();
        Flyweight f01=factory.getFlyweight("a");
        Flyweight f02=factory.getFlyweight("a");
        f01.operation(new UnFlyweight("1"));
        f02.operation(new UnFlyweight("2"));
    }
ConcreteFlyweight create a
Flyweight key a is already exist.
ConcreteFlyweight key is a. ConcreteFlyweight operation with unFlyweight[1]
ConcreteFlyweight key is a. ConcreteFlyweight operation with unFlyweight[2]

组合模式

有时又叫作部分-整体模式,它是一种将对象组合成树状的层次结构的模式,用来表示“部分-整体”的关系,使用户对单个对象和组合对象具有一致的访问性。

//组件接口
public interface MyComponent {
    void add(MyComponent c);
    void remove(MyComponent c);
    MyComponent getChild(int i);
    void operation();
}
//叶子实现接口
public class Leaf implements MyComponent{
    private String name;
    public Leaf(String name)
    {
        this.name=name;
    }
    public void add(MyComponent c){ }
    public void remove(MyComponent c){ }
    public MyComponent getChild(int i) {
        return null;
    }
    public void operation() {
        System.out.println("Leaf "+name+" is here");
    }
}
//树枝实现接口
public class Composite implements MyComponent{
    private ArrayList<MyComponent> children=new ArrayList<MyComponent>();
    public void add(MyComponent c){
        children.add(c);
    }
    public void remove(MyComponent c){
        children.remove(c);
    }
    public MyComponent getChild(int i) {
        return children.get(i);
    }
    public void operation() {
        for (MyComponent c : children) {
            c.operation();
        }
    }
}

Main方法及输出结果:

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

推荐阅读更多精彩内容