设计模式学习笔记(四):策略模式【Strategy】

    刘备要到江东娶老婆了,走之前诸葛亮给赵云三个锦囊妙计,说是按天机拆开解决棘手问题。

    三个妙计是同一类型的东西,写个接口如下:

package com.example;

/**
 * 首先定义一个策略接口,负责三个锦郎妙计的接口
 */
public interface IStrategy {

	//每个锦郎妙计都是一个可执行的算法
	public void operate();
}

     然后实现三个实现类,因为有三个妙计:

package com.example;

/**
 * 找乔国老帮忙,是孙权不能杀刘备
 */
public class BackDoor implements IStrategy{

	public void operate() {
		System.out.println("找乔国老帮忙,让吴国太给孙权施加压力");
	}
}
package com.example;

/**
 * 求吴国太给开个绿灯
 */
public class GivenGreenLight implements IStrategy{

	public void operate() {
		System.out.println("求吴国太开个绿灯,放行!");
	}
}
package com.example;

/*
 * 孙夫人断后,挡住追兵
 */
public class BlockEnemy implements IStrategy{

	public void operate() {
		System.out.println("孙夫人断后,挡住追兵!");
	}
}

    好了,三个妙计是有了,得有个锦囊要放这些妙计啊,锦囊定义如下:

package com.example;

/*
 * 计谋有了,那还要有个锦郎
 */
public class Context {
	//构造函数,你要使用哪一个妙计
	private IStrategy strategy;
	public Context(IStrategy strategy){
		this.strategy = strategy;
	}
	//计谋有了,看我出招了
	public void operater(){
		this.strategy .operate();
	}
}

     最后是赵云用了这三个锦囊化险为夷:

package com.example;

public class ZhaoYun {
	/*
	 * 赵云出场,他根据诸葛亮的交代一次拆开妙计
	 */
	public static void main(String[] args){
		Context context;
		//刚刚到吴国时候拆开第一个
		context = new Context(new BackDoor());
		context.operater();
		
		//刘备乐不思蜀,拆开了第二个
		context = new Context(new GivenGreenLight());
		context.operater();
		
		//孙权的小兵追了,咋办?拆开第三个
		context = new Context(new BlockEnemy());
		context.operater();
	}
}


      使用策略模式之后,代码的可读性和扩展性有了很大的提高,以后即使还需要添加新的算法,你也是手到擒来了。

       策略:它定义了算法家庭,分别封装起来。让他们之间可以互相替换,此模式让算法的变化不会影响到使用算法的用户。


package com.example;

public class ZhaoYun {
	/*
	 * 赵云出场,他根据诸葛亮的交代一次拆开妙计
	 */
	public static void main(String[] args){
		Context context;
		//刚刚到吴国时候拆开第一个
		context = new Context(new BackDoor());
		context.operater();
		
		//刘备乐不思蜀,拆开了第二个
		context = new Context(new GivenGreenLight());
		context.operater();
		
		//孙权的小兵追了,咋办?拆开第三个
		context = new Context(new BlockEnemy());
		context.operater();
	}
}


 

 

 

 





 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值