您的位置:首页 > 其它

设计模式学习笔记—策略模式

2016-01-24 20:51 106 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/LiynGu/article/details/50575340

策略模式(Strategy pattern)

这个模式的作用应该就是

想办法干掉 if else

准确来说应该是类似于switch那种。
然而,我感觉我的智商收到了侮辱。w(゚Д゚)w
(开个玩笑)
但实际上我确实不知道这样一种模式,怎么说呢,和工厂那边太像了吧!如果我理解的不错的话,经常用的三层架构基本上就是,工厂方法+策略模式,而不是完全的工厂方法,工厂方法负责获得对象,策略模式负责其它操作,不过那样,策略基本上会只有一种。
下面是我自己瞎编的一些代码。(๑•̀ㅂ•́)و✧

public interface HttpConnection {
// 都说了是乱写的了w(゚Д゚)w
void sendData(HttpMethod method);
}
public interface HttpMethod {
void execute();
}

先假定有这样两个接口,虽然实际上肯定不是这样的

public class HttpConnectionImpl implements HttpConnection {

@Override
public void sendData(HttpMethod method) {
method.execute();
}
}
public class GetMethod implements HttpMethod {
@Override
public void execute() {
System.out.println("using the get method");
}
}
public class PostMethod implements HttpMethod {
@Override
public void execute() {
System.out.println("using the post method");
}
}

调用的时候会是这样

public class Main {
public static void main(String[] args) {
HttpConnection conn = new HttpConnectionImpl();
conn.sendData(new GetMethod());
conn.sendData(new PostMethod());
}
}

而实际上,根本不会出现这种调用方法吧!
所以,去改造下 Connection

public interface HttpConnection {
void setMethod(String method);
void sendData();
}
public class HttpConnectionImpl implements HttpConnection {
private Map<String, HttpMethod> mMethodMap = new HashMap<String, HttpMethod>();
private String mMethod = "GET";

public HttpConnectionImpl() {
mMethodMap.put("GET", new GetMethod());
mMethodMap.put("POST", new PostMethod());
}

@Override
public void setMethod(String method) {
// 说好的干掉 if呢 Σ(っ °Д °;)っ
if (mMethodMap.containsKey(method.toUpperCase())) {
mMethod = method;
}
}

@Override
public void sendData() {
mMethodMap.get(mMethod).execute();
}
}

调用的话会变成这样,看起来舒服多了

public class Main {
public static void main(String[] args) {
HttpConnection conn = new HttpConnectionImpl();
conn.sendData();
conn.setMethod("POST");
conn.sendData();
}
}

感觉这种模式的诞生只是因为 java 没有委托,手动斜眼。
如果不用这种模式,应该就会是这样

public class HttpConnectionImpl implements HttpConnection {
private String mMethod = "GET";

@Override
public void setMethod(String method) {
mMethod = method;
}

@Override
public void sendData() {
switch (mMethod) {
case "POST":
System.out.println("using the post method");
break;
case "GET":
default:
System.out.println("using the get method");
break;
}
}
}

代码量明显少了很多,可读性也明显提高了很多,那为什么还要这种设计模式啊喂!
其实是为了一些可扩展性,还有,面向对象编程,是吧。

The end.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: