目前常用的设计模式有几十种,简单的死记硬除了面试外别无他用,更重要的是熟练运用到实际场景中去,去用好用对至关重要。本栏就从HelloWorld揭开设计模式的面纱。
下面是每个程序员的第一个程序。
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
用设计模式的视角去看,它并不优雅,不是吗?如果我想输入其他文本,或者修改字体呢。
用设计模式的思维去写,如下:
public interface MessageStrategy {
public void sendMessage();
}
public abstract class AbstractStrategyFactory {
public abstract MessageStrategy createStrategy(MessageBody mb);
}
public class MessageBody {
Object payload;
public Object getPayload() {
return payload;
}
public void configure(Object obj) {
payload = obj;
}
public void send(MessageStrategy ms) {
ms.sendMessage();
}
}
public class DefaultFactory extends AbstractStrategyFactory {
private DefaultFactory() {;}
static DefaultFactory instance;
public static AbstractStrategyFactory getInstance() {
if (instance==null) instance = new DefaultFactory();
return instance;
}
public MessageStrategy createStrategy(final MessageBody mb) {
return new MessageStrategy() {
MessageBody body = mb;
public void sendMessage() {
Object obj = body.getPayload();
System.out.println((String)obj);
}
};
}
}
public class HelloWorld {
public static void main(String[] args) {
MessageBody mb = new MessageBody();
mb.configure("Hello World!");
AbstractStrategyFactory asf = DefaultFactory.getInstance();
MessageStrategy strategy = asf.createStrategy(mb);
mb.send(strategy);
}
}
这样写看起来很吊吧,光看懂就要好长时间,哈哈,好卷!