设计模式--策略模式

来源:互联网 发布:知我药妆网假货多吗 编辑:程序博客网 时间:2024/06/05 20:29

概念:将一些算法封装,定义成一个抽象的算法接口,由具体的实现类来实现具体的算法,具体的算法选择交给客户端决定。
类图如下:
这里写图片描述

Strategy.javapackage com.gingko;public interface Strategy {    //encrypt algorithm    public void encryptAlgorithm();}RSAEncrypt.javapackage com.gingko;/** * RAS encrypt algorithm */public class RSAEncrypt implements Strategy{    @Override    public void encryptAlgorithm() {        System.out.println("invoke RSA encrypt algorithm...");    }}DESEncrypt.javapackage com.gingko;/** * DES Encrypt algorithm */public class DESEncrypt implements Strategy{    @Override    public void encryptAlgorithm() {        System.out.println("invoke DES encrypt algorithm...");    }}Context.javapackage com.gingko;public class Context {    private Strategy strategy;    public Context(Strategy strategy) {        super();        this.strategy = strategy;    }    public void encryptAlgorithm() {        this.strategy.encryptAlgorithm();    }}

测试:具体的算法选择交给客户端决定

package com.gingko;public class Client {    public static void main(String[] args) {        //reference different strategy        Context context = new Context(new DESEncrypt());        context.encryptAlgorithm();        context = new Context(new RSAEncrypt());        context.encryptAlgorithm();    }}

测试结果:
invoke DES encrypt algorithm…
invoke RSA encrypt algorithm…

0 0
原创粉丝点击