设计模式-策略模式

Define a family of algorithms, encapsulate each one, and make them interchangeable.
	定义一组算法,将每个算法都封装起来,并且使它们之间可以互换。
	
	public interface Strategy {
	
		public void doSomething();
		
	}
	
	public class ConcreteStrategy1 implements Strategy {

		@Override
		public void doSomething() {
			System.out.println("ConcreteStrategy1 doSomething.");
		}

	}
	
	public class ConcreteStrategy2 implements Strategy {

		@Override
		public void doSomething() {
			System.out.println("ConcreteStrategy2 doSomething.");
		}

	}
	
	public class Context {

		private Strategy strategy;
		
		public Context(Strategy strategy) {
			this.strategy = strategy;
		}
		
		public void doAnything() {
			this.strategy.doSomething();
		}
	}
	
	public class Client {

		public static void main(String[] args) {
			
			Strategy strategy = new ConcreteStrategy1();
			Context context = new Context(strategy);
			context.doAnything();
		}

	}
	
	策略模式的优点
	(1)算法可以自由切换
	(2)避免使用多重条件判断
	(3)扩展性好
	
	策略模式使用的场景
	(1)多个类只有在算法或行为上稍有不同的场景
	(2)算法需要自由切换
	(3)需要屏蔽算法规则的场景
	
	策略模式的扩展
	public enum Calculators {

		ADD("+") {
			public int exec(int a, int b) {
				return a+b;
			}
		},
		SUB("-") {
			public int exec(int a, int b) {
				return a-b;
			}
		};
		
		String value = "";
		
		private Calculators(String value) {
			this.value = value;
		}
		
		public String getValue() {
			return this.value;
		}
		
		public abstract int exec(int a, int b);
	}

出自 设计模式之禅 秦小波

你可能感兴趣的:(设计模式)