代码设计:设计模式:委托模式

文章目录

定义

委托,指的是调用被依赖的类的方法

类A依赖类B,一般都是A调用B的方法,但委托是B调用A的方法

类结构

委托接口

委托接口可以是独立接口,也可以是被委托类中的内部接口

定义抽象的委托方法

被委托者类

封装一个具体的方法,用于实现某个功能

创建一个委托接口的对象,调用具体的方法

持有一个委托者对象,把委托者接口对象注入委托者对象中

委托者类

持有一个委托接口对象,调用委托方法,即调用被委托者的具体的方法

类之间的关系

被委托者依赖委托者,但委托者调用被委托者的方法,这就是依赖反转(依赖注入)

代码实例

委托接口

委托接口可以是独立接口,也可以是被委托类中的内部接口

复制代码
public interface Delegation {

    void delegate()
}

被委托类和委托接口

复制代码
public class Deleagted {


    private Delegator delegator;

    public void method(){
        
        delegator.setDelegation(new Delegation() {

            public void delegate() {

                Delegated.this.doSomething();
            }
        })
    }

    public void doSomething() {

        ... ...
    }
}

​​​​​​​委托者类

复制代码
public class Delegator {

    private Delegation delegation;

    public void setDelegation(Delegation delegation) {

        this.delegation = delegation;
    }

    public void doSomething() {

        ... ...
        delegation.delegate();
        ... ...
    }
}

总结

被委托者依赖委托者,但委托者调用被委托者的方法,这就是依赖反转(依赖注入)

相关推荐
李广坤1 小时前
状态模式(State Pattern)
设计模式
李广坤3 小时前
观察者模式(Observer Pattern)
设计模式
李广坤3 小时前
中介者模式(Mediator Pattern)
设计模式
李广坤4 小时前
迭代器模式(Iterator Pattern)
设计模式
李广坤4 小时前
解释器模式(Interpreter Pattern)
设计模式
阿无,7 小时前
java23种设计模式之前言
设计模式
Asort8 小时前
JavaScript设计模式(八):组合模式(Composite)——构建灵活可扩展的树形对象结构
前端·javascript·设计模式
数据智能老司机8 小时前
数据工程设计模式——数据基础
大数据·设计模式·架构
笨手笨脚の10 小时前
设计模式-代理模式
设计模式·代理模式·aop·动态代理·结构型设计模式
Overboom18 小时前
[C++] --- 常用设计模式
开发语言·c++·设计模式