1. 程式人生 > >策略模式【行為模式】

策略模式【行為模式】

策略模式

策略模式:
Define a family or algorithms,encapsulate each one,and make them interchangeable.
定義一組演算法,將每個演算法都封裝起來,並且使得它們可以互換。
@Slf4j
public class Strategy {
    /**
     * 策略模式:
     * Define a family or algorithms,encapsulate each one,and make them interchangeable.
     * 定義一組演算法,將每個演算法都封裝起來,並且使得它們可以互換。
     */

    @Test
    public void testStrategy() {
        final Context context = new Context("hello world");
        final TextStrategy textStrategy = TextStrategy.builder().build();
        final HtmlStrategy htmlStrategy = HtmlStrategy.builder().build();
        final XmlStrategy xmlStrategy = XmlStrategy.builder().build();
        /**
         * 切換策略
         */
        doInvoke(context, textStrategy);
        doInvoke(context, htmlStrategy);
        doInvoke(context, xmlStrategy);
    }

    private void doInvoke(Context context, IStrategy textStrategy) {
        context.changeStrategy(textStrategy);
        log.info(context.invoke());
    }
}

/**
 * 1)定義所有策略的核心介面
 */
interface IStrategy {
    String execute(String t);
}
/**
 * 2)定義具體的策略實現
 */
@Builder
class TextStrategy implements IStrategy {
    @Override
    public String execute(String t) {
        return t;
    }

}
@Builder
class HtmlStrategy implements IStrategy {

    @Override
    public String execute(String t) {
        return "<html><head><title>Empty</title></head><h3>#<h3></body></html>".replace("#", t);
    }

}
@Builder
class XmlStrategy implements IStrategy {

    @Override
    public String execute(String t) {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><target>#</target>".replace("#", t);
    }

}

/**
 * 3)定義一個上下文,用於切換策略
 */
@Builder
@AllArgsConstructor
class Context {
    private IStrategy strategy;
    private final String target;

    public Context(String target) {
        super();
        this.target = target;
    }

    public void changeStrategy(IStrategy strategy) {
        this.strategy = strategy;
    }

    public String invoke() {
        return strategy.execute(target);
    }
}