public interface OrderService {
void saveOrder(String orderNo);
}
public class MySqlSaveOrderStrategy implements OrderService {
@Override
public void saveOrder(String orderNo) {
System.out.println("order:" + orderNo + " save to mysql");
}
}
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 OrderServiceExecutor {
private final OrderService service;
public OrderServiceExecutor(OrderService service) {
this.service = service;
}
public void save(String orderNo) {
this.service.saveOrder(orderNo);
}
}
1
2
3
4
5
6
7
8
9
10
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");
}
}
用 lambda重构后,可以省去2个策略实现类
1
2
3
4
5
6
7
8
9
10
11
public class OrderServiceTest {
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");
}
}
import java.util.*;
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) {
for (Observer observer : list) {
observer.notify(orderNo);
}
}
}
观察者的两个实现
1
2
3
4
5
6
7
8
public class OrderObserver implements Observer {
@Override
public void notify(String orderNo) {
System.out.println("订单 " + orderNo + " 状态更新为【已支付】");
}
}
1
2
3
4
5
6
7
8
public class StockObserver implements Observer {
@Override
public void notify(String orderNo) {
System.out.println("订单 " + orderNo + " 已通知库房发货!");
}
}
1
2
3
4
5
6
7
public static void main(String[] args) {
Subject subject = new SubjectImpl();
subject.registerObserver(new OrderObserver());
subject.registerObserver(new StockObserver());
subject.notifyAllObserver("001");
}
java8 接口可以提供默认实现方法,弄一个新的主题接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.util.*;
public interface NewSubject {
List<Observer> list = new ArrayList<>();
default void registerObserver(Observer o) {
list.add(o);
}
default void nofityAllObserver(String orderNo) {
for (Observer observer : list) {
observer.notify(orderNo);
}
}
}