策略模式

策略模式

首先上一张策略模式的基本类图:

上面的这张图就是策略模式的基本类图,那么我们可以看出策略模式其实和简单工厂模式非常像,但是还是有点区别的,简单工厂模式中是采用工厂类来解决来创建,降低代码的耦合性的,那么策略模式呢?

策略模式一般用在封装一些(但是不局限)算法,在某一个功能上有不同的算法需要实现,比如排序(冒泡排序,快速排序,插入排序等)

那么现在来看看具体策略模式是怎么降低代码的耦合性的:

实:

策略模式抽象类(Strategy)
	public abstract class Strategy {
	
		public abstract void algorithmInterface();//抽象算法
	
	}
算法A类(StrategyA)
	public class StrategyA extends Strategy {

		public void algorithmInterface() {
			System.out.println("算法A实现");
		}
	
	}
算法B类(StrategyB)
	public class StrategyB extends Strategy {

		@Override
		public void algorithmInterface() {
			System.out.println("算法B实现");
		}
	}
算法C类(StrategyC)
	public class StrategyC extends Strategy {

		@Override
		public void algorithmInterface() {
			System.out.println("算法C实现");
		}
	
	}
上下文类(Context)
	public class Context {
		public Strategy strategy;
		
		public Context(Strategy strategy){
			this.strategy = strategy;//初始化传入具体的算法对象
		}
		//根据具体的算法对象创建具体的算法
		public void contextInterface(){
			strategy.algorithmInterface();
		}
	}
客户端实现
	public class StrategyMain {
		public static void main(String[] args){
			//创建算法A
			Context context = new Context(new StrategyA());
			context.contextInterface();//算法A实现
			
			//创建算法B
			context = new Context(new StrategyB());
			context.contextInterface();//算法B实现
	
			//创建算法C
			context = new Context(new StrategyC());
			context.contextInterface();//算法C实现
		}
	}

那么通过这个简单的策略模式的实现我们能看出,当我们在客户端使用某一个定义好的算法的时候我们不需要去管其他的类,我们只需要通过上下文(Context)这个类,传入一个实体对象就可以创建想要使用的算法,通过这样的手段来降低程序的耦合性。

这个只是简单的实例,也是策略模式的基本模型。
在我们的使用过程中,我们可以和其他设计模式一起使用,也就是综合运用的体现。

记录学习的每一步,记录每一步的成长!!!!

原文地址:https://www.cnblogs.com/mojita/p/5187072.html