标签:dia system coding pattern odi contex demo nta 方法
策略模式:封装的是做一个事情的具体方法。封装以后可以选择任意的具体的方法。
实现:
各种具体方法使用Strategy接口,Context包含了strategy,通过改变它来调用不同的strategy
接口
public interface IMedia {
public void connect(String name);
}
各种策略
public class WeChatMedia implements IMedia {
@Override
public void connect(String name) {
System.out.println("connecting " + name + " with WeChat");
}
}
public class AlibabaMedia implements IMedia {
@Override
public void connect(String name) {
System.out.println("Connecting " + name + " with Alibaba");
}
}
public class QQMedia implements IMedia {
@Override
public void connect(String name) {
System.out.println("Connecting " + name + " with QQ");
}
}
Context class
public class MediaImp {
private IMedia iMedia;
public void setiMedia(IMedia iMedia){
this.iMedia = iMedia;
}
public void connect(String name) {
iMedia.connect(name);
}
}
测试:
public class Demo {
public static void main(String[] args) {
MediaImp media = new MediaImp();
media.setiMedia(new WeChatMedia());
media.connect("codingEskimo");
media.setiMedia(new QQMedia());
media.connect("codingEskimo");
media.setiMedia(new AlibabaMedia());
media.connect("codingEskimo");
}
}
结果
connecting codingEskimo with WeChat
Connecting codingEskimo with QQ
Connecting codingEskimo with Alibaba
[DesignPattern]设计模式:策略(Strategy)
标签:dia system coding pattern odi contex demo nta 方法
原文地址:https://www.cnblogs.com/codingEskimo/p/13052906.html