起源:https://www.cnblogs.com/yjmyz…
java8 中提供的很多新个性能够用来重构传统设计模式中的写法,上面是一些示例:
一、策略模式
上图是策略模式的类图,假如咱们当初要保留订单,OrderService
接口定义要做什么,而 NoSqlSaveOrderStragegy
以及 MySqlSaveOrderStrategy
则提供了二种策略,别离是保留到 nosql 数据库,以及传统的 mysql 关系型数据库,最初在 OrderServiceExecutor
中通过构造函数注入最终要应用的策略。
传统写法,这个场景至多得 4 个类,代码如下:
OrderService
接口:
public interface OrderService {void saveOrder(String orderNo);
}
Mysql 策略实现:
public class MySqlSaveOrderStrategy implements OrderService {
@Override
public void saveOrder(String orderNo) {System.out.println("order:" + orderNo + "save to mysql");
}
}
Nosql 策略实现
public class NoSqlSaveOrderStrategy implements OrderService {
@Override
public void saveOrder(String orderNo) {System.out.println("order:" + orderNo + "save to nosql");
}
}
Spring Boot 根底就不介绍了,举荐下这个实战教程:
https://github.com/javastacks…
应用策略的辅助 ” 容器 ”
public class OrderServiceExecutor {
private final OrderService service;
public OrderServiceExecutor(OrderService service) {this.service = service;}
public void save(String orderNo) {this.service.saveOrder(orderNo);
}
}
运行测试类:
public class OrderServiceTest {public static void main(String[] args) {OrderServiceExecutor executor1 = new OrderServiceExecutor(new MySqlSaveOrderStrategy());
executor1.save("001");
OrderServiceExecutor executor2 = new OrderServiceExecutor(new NoSqlSaveOrderStrategy());
executor2.save("002");
}
}
重构后,能够省去 2 个策略实现类,代码如下:
public static void main(String[] args) {OrderServiceExecutor executor1 = new OrderServiceExecutor((String orderNo) -> System.out.println("order:" + orderNo + "save to mysql"));
executor1.save("001");
OrderServiceExecutor executor2 = new OrderServiceExecutor((String orderNo) -> System.out.println("order:" + orderNo + "save to nosql"));
executor2.save("002");
}
学习材料分享:https://www.javastack.cn/study/
二、模板办法
类图如下,外围思路是把一些通用的规范办法,在形象父类里仅定义方法签名,实现逻辑交给子类。
比方:会员零碎中,每个商家都会有一些营销流动,须要推送某种信息给会员,然而不同的商家推送的内容可能不同,有些须要推送优惠券,有些须要积分告诉。
形象模板类:
public abstract class AbstractPushTemplate {public void push(int customerId, String shopName) {System.out.println("筹备推送...");
execute(customerId, shopName);
System.out.println("推送实现 \n");
}
abstract protected void execute(int customerId, String shopName);
}
优惠券的具体模板
public class PushCouponTemplate extends AbstractPushTemplate {
@Override
protected void execute(int customerId, String shopName) {System.out.println("会员:" + customerId + ", 你好," + shopName + "送您一张优惠券");
}
}
积分的具体模板
public class PushScoreTemplate extends AbstractPushTemplate {
@Override
protected void execute(int customerId, String shopName) {System.out.println("会员:" + customerId + ", 你好," + shopName + "送您 10 个积分");
}
}
应用示例:
AbstractPushTemplate template1 = new PushCouponTemplate();
template1.push(1, "糖果店");
AbstractPushTemplate template2 = new PushScoreTemplate();
template2.push(1, "服装店");
显然如果模板的实现形式越多,子类就越多。应用 java8 重构后,能够把下面的 3 个模板(包含抽象类模板)缩小到 1 个,参考上面:
public class PushTemplateLambda {public void push(int customerId, String shopName, Consumer<Object[]> execute) {System.out.println("筹备推送...");
Object[] param = new Object[]{customerId, shopName};
execute.accept(param);
System.out.println("推送实现 \n");
}
}
借助Consumer<T> 这个 function interface
,能够省去实现子类,具体的实现留到应用时再来决定,如:
new PushTemplateLambda().push(1, "糖果店", (Object[] obj) -> {System.out.println("会员:" + obj[0] + ", 你好," + obj[1] + "送您一张优惠券");
});
new PushTemplateLambda().push(1, "服装店", (Object[] obj) -> {System.out.println("会员:" + obj[0] + ", 你好," + obj[1] + "送您 10 个积分");
});
三、观察者模式
思路:基于某个 Subject 主题,而后一堆观察者 Observer 注册到主题上,有事件产生时,subject 依据注册列表,去告诉所有的 observer。
Observer 接口:
public interface Observer {void notify(String orderNo);
}
另外,Java 系列面试题和答案全副整顿好了,微信搜寻 Java 技术栈,在后盾发送:面试,能够在线浏览。
Subject 接口:
public interface Subject {void registerObserver(Observer o);
void notifyAllObserver(String orderNo);
}
Subject 接口实现:
public class SubjectImpl implements Subject {private final List<Observer> list = new ArrayList<>();
@Override
public void registerObserver(Observer o) {list.add(o);
}
@Override
public void notifyAllObserver(String orderNo) {list.forEach(c -> c.notify(orderNo));
}
}
观察者的二个实现:
OrderObserver:
public class OrderObserver implements Observer {
@Override
public void notify(String orderNo) {System.out.println("订单" + orderNo + "状态更新为【已领取】");
}
}
StockObserver:
public class StockObserver implements Observer {
@Override
public void notify(String orderNo) {System.out.println("订单" + orderNo + "已告诉库房发货!");
}
}
测试一把:
static void test1() {Subject subject = new SubjectImpl();
subject.registerObserver(new OrderObserver());
subject.registerObserver(new StockObserver());
subject.notifyAllObserver("001");
}
用 java8 重构后,接口能够提供默认实现办法,咱们弄一个新的主题接口
public interface NewSubject {List<Observer> list = new ArrayList<>();
default void registerObserver(Observer o) {list.add(o);
}
default void nofityAllObserver(String orderNo) {list.forEach(c -> c.notify(orderNo));
}
}
应用:
static void test2() {NewSubject subject = new NewSubject() { };
subject.registerObserver((String orderNo) -> System.out.println("订单" + orderNo + "状态更新为【已领取】"));
subject.registerObserver((String orderNo) -> System.out.println("订单" + orderNo + "已告诉库房发货!"));
subject.nofityAllObserver("002");
}
只用 2 个接口实现了观察者模式。
四、责任链 / 职责链模式
核心思想:每个解决环节,都有一个“指针”指向下一个解决者,相似链表一样。
Processor 接口:
public interface Processor {Processor getNextProcessor();
void process(String param);
}
形象实现类
public abstract class AbstractProcessor implements Processor {
private Processor next;
public AbstractProcessor(Processor processor) {this.next = processor;}
@Override
public Processor getNextProcessor() {return next;}
@Override
public abstract void process(String param);
}
定义 2 个具体的实现
public class ProcessorImpl1 extends AbstractProcessor {public ProcessorImpl1(Processor processor) {super(processor);
}
@Override
public void process(String param) {System.out.println("processor 1 is processing:" + param);
if (getNextProcessor() != null) {getNextProcessor().process(param);
}
}
}
及
public class ProcessorImpl2 extends AbstractProcessor {public ProcessorImpl2(Processor next) {super(next);
}
@Override
public void process(String param) {System.out.println("processor 2 is processing:" + param);
if (getNextProcessor() != null) {getNextProcessor().process(param);
}
}
}
应用示例:
static void test1() {Processor p1 = new ProcessorImpl1(null);
Processor p2 = new ProcessorImpl2(p1);
p2.process("something happened");
}
用 java8 重构后,只须要一个新接口
@FunctionalInterface
public interface NewProcessor {Consumer<String> process(String param);
}
同样的成果,能够写得很简洁:
static void test2() {Consumer<String> p1 = param -> System.out.println("processor 1 is processing:" + param);
Consumer<String> p2 = param -> System.out.println("processor 2 is processing:" + param);
p2.andThen(p1).accept("something happened");
}
andThen 人造就是 getNextProcessor 的另一种表白。
重要提醒:什么时候该用 lambda,什么时候不必,这是要看状况的,如果解决逻辑绝对比较简单,能够用 lamdba 来重构,以便让代码更简洁易读,如果解决逻辑很简单,应该还是用“类”。
近期热文举荐:
1.1,000+ 道 Java 面试题及答案整顿(2022 最新版)
2. 劲爆!Java 协程要来了。。。
3.Spring Boot 2.x 教程,太全了!
4. 别再写满屏的爆爆爆炸类了,试试装璜器模式,这才是优雅的形式!!
5.《Java 开发手册(嵩山版)》最新公布,速速下载!
感觉不错,别忘了顺手点赞 + 转发哦!