[设计模式]委派模式

github地址:https://github.com/1711680493

点我进入github

如需了解更多设计模式,请进入我的设计模式专栏


委派模式

委派模式不是23设计模式中的一种.

与策略模式很相似.

拥有以下三种角色

  1. 抽象任务角色
  2. 委派者角色
  3. 具体任务角色

委派模式,就是将任务发给委派者角色,委派者角色去委派具体任务角色

委派模式对外隐藏了具体实现,仅将委派者角色暴露给外部

委派模式和策略模式不同的是,委派者角色和具体任务角色都要继承/实现抽象任务角色

Spring框架很多地方用到了委派模式,例如 Dispatcher(转发)


代码实现


/**
 * 委派模式
 * @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a>
 * @version 1.0
 */
public class DelegatePattern {

	public static void main(String[] args) {
		DelegateAbstract p = new DelegatePlayer();
		p.exec("A");
		p.exec("B");
		p.exec("???");
	}
	
}

/**
 * 抽象任务角色
 * @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a>
 * @version 1.0
 */
interface DelegateAbstract {

	/**
	 * 执行对应任务.
	 * @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a>
	 * @param name 委派名
	 */
	void exec(String name);
	
}

/**
 * 委派者
 * @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a>
 * @version 1.0
 */
class DelegatePlayer implements DelegateAbstract {

	@Override
	public void exec(String name) {
		
		// 将请求委派给别人
		// 这里使用HashMap,在被创建的时候进行初始化
		DelegateAbstract d = null;
		if ("A".equals(name)) {
			d = new DelegateA();
		} else if ("B".equals(name)) {
			d = new DelegateB();
		} else {
			System.out.println("我是委派者,没有此任务角色: " + name);
		}
		if (d != null) d.exec(name);
	}
	
}

/**
 * 具体任务角色A
 * @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a>
 * @version 1.0
 */
class DelegateA implements DelegateAbstract {

	@Override
	public void exec(String name) {
		System.out.println("我是任务A");
	}
	
}

/**
 * 具体任务角色B
 * @author Shendi <a href='tencent://AddContact/?fromId=45&fromSubId=1&subcmd=all&uin=1711680493'>QQ</a>
 * @version 1.0
 */
class DelegateB implements DelegateAbstract {

	@Override
	public void exec(String name) {
		System.out.println("我是任务B");
	}
	
}

运行结果如下

猜你喜欢

转载自blog.csdn.net/qq_41806966/article/details/107485845