工厂模式 - 969251639/study GitHub Wiki

场景:接收微信的推送消息,不同的消息通过不同的handler来处理,那么如何根据不同的消息产生不同的handler,可以使用简单工厂模式来实现

  1. 定义处理的接口
public interface BaseHandler {
	public String produce(WXMessageBase message);
}
  1. 实现接口的具体实现类,也就是具体处理消息的类
//处理点击事件
public class ClickHandler implements BaseHandler {
        @Override
	public String produce(WXMessageBase message) {
            ...
        }
}
//处理扫描事件,比如二维码  
public class ScanHandler implements BaseHandler {
        @Override
	public String produce(WXMessageBase message) {
            ...
        }
}
//获取地理位置事件
public class LocationHandler implements BaseHandler {
        @Override
	public String produce(WXMessageBase message) {
            ...
        }
}

...
  1. 根据不同的消息在工厂获取这些handler
//抽象公共的消息体
public class WXMessageBase {
    ...
}
//微信中的事件
public class WXReceivedEvent extends WXMessageBase {
    ...
}
//点击事件
public class WXReceivedClickEvent extends WXReceivedEvent {
    ...
}
//地理位置事件
public class WXReceivedLocationEvent extends WXReceivedEvent {
    ...
}
//扫描事件
public class WXReceivedScanEvent extends WXReceivedEvent {
    ...
}
...

//简单工厂实现
public class HandlerFactory {
	public static BaseHandler createHandler(WXMessageBase message) {
		if (message instanceof WXReceivedScanEvent) {//如果是扫描事件消息
			return (ScanHandler) SpringContainerTools.getBean("scanHandler");
		}
		if (message instanceof WXReceivedLocationEvent) {//如果是获取地理位置事件消息
			return (LocationHandler) SpringContainerTools.getBean("locationHandler");
		}
		if (message instanceof WXReceivedClickEvent) {//如果是单机事件消息
			return (ClickHandler) SpringContainerTools.getBean("clickHandler");
		}
		...
		return null;
	}
}