1.概念相关
<1>策略模式:它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户.
2.策略模式UML图
3.java代码示例
package com.fr.designpattern.ch02strategy.pattern;
public class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void contextInteface(){
if (strategy!=null) {
strategy.algorithmInteface();
}
}
}
package com.fr.designpattern.ch02strategy.patterncombination;
public class Context {
private Strategy strategy;
/**策略模式与简单工厂相结合*/
public Context(String type) {
switch (type) {
case "A":
this.strategy = new ConcreteStrategyA();
break;
case "B":
this.strategy = new ConcreteStrategyB();
break;
case "C":
this.strategy = new ConcreteStrategyC();
break;
default:
break;
}
}
public void contextInteface(){
if (strategy!=null) {
strategy.algorithmInteface();
}
}
}
4.OOP
<1>面向对象的编程并不是类越多越好,类的划分是为了封装,但分类的基础是抽象,具有相同属性和功能的对象的抽象集合才是类;
<2>封装变化点是面向对象的一种重要思维方式;策略模式封装了变化;