爱编程,爱生活

Java设计模式<策略模式>

2018-06-16  本文已影响11人  熬夜的猫头鹰

Java设计模式<策略模式>

意图

解决的问题

场景

优点

Demo

现实场景中是进行签名的方法包括为Md5 RSA RSA2

创建签名接口

public interface  Sign {

    public String sign(String str);
}

实现类RSA

public class RSASign implements Sign{
    public String sign(String str) {
        System.err.println("using RSA to sign the string");
        return null;
    }
}

实现类RSA2

public class RSA2Sign implements Sign{
    public String sign(String str) {
        System.err.println("using RSA2 to sign the string");
        return null;
    }
}

MD5Sign

public class MD5Sign implements Sign {
    public String sign(String str) {
        System.err.println("using MD5 to sign the string");
        return null;
    }
}

创建上下文类

public class Context {

    private Sign strategy;

    public Context(Sign strategy) {
        this.strategy = strategy;
    }

    public Sign getStrategy() {
        return strategy;
    }

    public void setStrategy(Sign strategy) {
        this.strategy = strategy;
    }

    public String operate(String str){
    return this.getStrategy().sign(str);
    }

}

测试类DemoMain

public class DemoMain {
    public static void main(String[] args) {
        Context context = new Context(new MD5Sign());
        context.operate("Jeffy");
    }
}

输出

using MD5 to sign the string
上一篇 下一篇

猜你喜欢

热点阅读