版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/t1g2q3/article/details/88067941
public void sendMessage(String type){
if("sms".equals(type)){
sendSms();
}else if("email".equals(type)){
sendEmail();
}
...
}
/**
* 模板引擎基类
* 所有模板类继承此类
* @author 李熠
*
*/
public abstract class Template {
//发送消息
public abstract void send(String jsonData)throws Exception;
}
//短信模板
public class SmsTemplate extends Template {
@Override
public void send(String jsonData)throws Exception{
// do something ...
}
}
public class TemplateFactory {
public static Template create(Type type){
Template template = null;
switch (type){
case SMS:
template = new SmsTemplate();
break;
case EMAIL:
template = new EmailTemplate();
break;
}
return template;
}
public static void main(String[] args) {
Template template = TemplateFactory.create(Type.SMS);
template.send(...);
}
}
if(情况1){
执行策略1
}else if(情况2){
执行策略2
}
public interface Strategy {
/**
* 策略方法
*/
void strategyInterface();
}
public class ConcreteStrategyA implements Strategy{
@Override
public void strategyInterface() {
System.out.println("实现策略1");
}
}
public class Context {
//持有一个具体策略的对象
private Strategy strategy;
/**
* 构造函数,传入一个具体策略对象
* @param strategy 具体策略对象
*/
public Context(Strategy strategy){
this.strategy = strategy;
}
/**
* 策略方法
*/
public void contextInterface(){
strategy.strategyInterface();
}
public static void executeStrategy(int type){
Strategy strategy = null;
if(type == 1){
strategy = new ConcreteStrategyA();
}
Context context = new Context(strategy);
context.contextInterface();
}
public static void main(String[] args) {
Context.executeStrategy(1);
}
}