标签:build 策略模式 java class 上下文 void psu his head
策略模式:
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);
}
}
标签:build 策略模式 java class 上下文 void psu his head
原文地址:https://www.cnblogs.com/zhuxudong/p/10164720.html