├── .gitignore ├── src ├── test │ └── java │ │ └── org │ │ └── ddd │ │ ├── example │ │ ├── inforstructure │ │ │ ├── data │ │ │ │ ├── ItemFieldPO.java │ │ │ │ ├── OrderItemPO.java │ │ │ │ └── OrderPO.java │ │ │ ├── mapper │ │ │ │ ├── OrderMapper.java │ │ │ │ ├── OrderItemMapper.java │ │ │ │ └── ItemFieldMapper.java │ │ │ └── repository │ │ │ │ └── OrderRepositoryImpl.java │ │ ├── domain │ │ │ ├── repository │ │ │ │ └── OrderRepository.java │ │ │ ├── aggregate │ │ │ │ ├── ShippingAddress.java │ │ │ │ ├── ItemField.java │ │ │ │ ├── OrderItem.java │ │ │ │ └── Order.java │ │ │ └── factory │ │ │ │ └── OrderFactory.java │ │ ├── application │ │ │ ├── data │ │ │ │ ├── request │ │ │ │ │ ├── ItemFieldRequest.java │ │ │ │ │ ├── ShippingAddressRequest.java │ │ │ │ │ ├── OrderItemRequest.java │ │ │ │ │ └── OrderRequest.java │ │ │ │ └── response │ │ │ │ │ ├── ShippingAddressResponse.java │ │ │ │ │ ├── ItemFieldResponse.java │ │ │ │ │ ├── OrderItemResponse.java │ │ │ │ │ └── OrderResponse.java │ │ │ ├── PlaceOrderService.java │ │ │ └── factory │ │ │ │ └── OrderFactoryImpl.java │ │ └── test │ │ │ └── OrderServiceTest.java │ │ └── helper │ │ └── SuppliersTest.java └── main │ └── java │ └── org │ └── ddd │ └── helper │ ├── As.java │ └── Suppliers.java ├── pom.xml ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea/ 2 | /target/ 3 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/inforstructure/data/ItemFieldPO.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.inforstructure.data; 2 | 3 | public class ItemFieldPO { 4 | private Integer id; 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/org/ddd/helper/As.java: -------------------------------------------------------------------------------- 1 | package org.ddd.helper; 2 | 3 | import java.util.function.Supplier; 4 | 5 | public interface As extends Supplier { 6 | boolean isHere(); 7 | } 8 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/inforstructure/data/OrderItemPO.java: -------------------------------------------------------------------------------- 1 | 2 | package org.ddd.example.inforstructure.data; 3 | 4 | import lombok.Data; 5 | 6 | @Data 7 | public class OrderItemPO { 8 | private Integer id; 9 | } 10 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/domain/repository/OrderRepository.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.domain.repository; 2 | 3 | import org.ddd.example.domain.aggregate.Order; 4 | 5 | public interface OrderRepository { 6 | Order save(Order order); 7 | Order get(String orderNo); 8 | } 9 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/application/data/request/ItemFieldRequest.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.application.data.request; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class ItemFieldRequest { 7 | private String key; 8 | private String type; 9 | private String value; 10 | } 11 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/inforstructure/mapper/OrderMapper.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.inforstructure.mapper; 2 | 3 | import org.ddd.example.inforstructure.data.OrderPO; 4 | 5 | public interface OrderMapper { 6 | OrderPO save(OrderPO order); 7 | 8 | OrderPO get(String orderNo); 9 | } 10 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/application/data/request/ShippingAddressRequest.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.application.data.request; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class ShippingAddressRequest { 7 | private String receiverName; 8 | private String phone; 9 | private String address; 10 | } 11 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/application/data/response/ShippingAddressResponse.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.application.data.response; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class ShippingAddressResponse { 7 | private String receiverName; 8 | private String phone; 9 | private String address; 10 | } 11 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/application/data/response/ItemFieldResponse.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.application.data.response; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class ItemFieldResponse { 7 | private Integer id; 8 | private String key; 9 | private String type; 10 | private String value; 11 | } 12 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/application/data/response/OrderItemResponse.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.application.data.response; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class OrderItemResponse { 7 | private Integer id; 8 | private String name; 9 | private String skuId; 10 | private Integer price; 11 | } 12 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/domain/aggregate/ShippingAddress.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.domain.aggregate; 2 | 3 | import lombok.Builder; 4 | import lombok.Getter; 5 | 6 | @Getter 7 | @Builder 8 | public class ShippingAddress { 9 | private String receiverName; 10 | private String phone; 11 | private String address; 12 | } 13 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/domain/aggregate/ItemField.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.domain.aggregate; 2 | 3 | import lombok.Builder; 4 | import lombok.Getter; 5 | 6 | @Getter 7 | @Builder 8 | public class ItemField { 9 | private Integer id; 10 | private String key; 11 | private String type; 12 | private String value; 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/inforstructure/mapper/OrderItemMapper.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.inforstructure.mapper; 2 | 3 | import org.ddd.example.inforstructure.data.OrderItemPO; 4 | 5 | import java.util.List; 6 | 7 | public interface OrderItemMapper { 8 | OrderItemPO[] save(OrderItemPO[] orderItemPO); 9 | 10 | List findBy(Integer orderId); 11 | } 12 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/inforstructure/data/OrderPO.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.inforstructure.data; 2 | 3 | import lombok.Data; 4 | 5 | @Data 6 | public class OrderPO { 7 | public String no; 8 | private Integer id; 9 | private Integer totalPrice; 10 | private String receiverName; 11 | private String phone; 12 | private String address; 13 | private String remark; 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/inforstructure/mapper/ItemFieldMapper.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.inforstructure.mapper; 2 | 3 | import org.ddd.example.inforstructure.data.ItemFieldPO; 4 | 5 | import java.util.List; 6 | 7 | public interface ItemFieldMapper { 8 | static List findBy(Integer itemId) { 9 | return null; 10 | } 11 | 12 | ItemFieldPO[] save(ItemFieldPO[] itemFieldPO); 13 | } 14 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/application/data/request/OrderItemRequest.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.application.data.request; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.List; 6 | 7 | @Data 8 | public class OrderItemRequest { 9 | private String name; 10 | private String skuId; 11 | private Integer price; 12 | private List fields = List.of(); 13 | private String remark; 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/application/data/response/OrderResponse.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.application.data.response; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.List; 6 | 7 | @Data 8 | public class OrderResponse { 9 | 10 | private Integer id; 11 | private String no; 12 | private Integer totalPrice; 13 | private List items; 14 | private ShippingAddressResponse shippingAddress; 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/application/data/request/OrderRequest.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.application.data.request; 2 | 3 | import lombok.Data; 4 | 5 | import java.util.List; 6 | import java.util.Optional; 7 | 8 | @Data 9 | public class OrderRequest { 10 | private Optional no = Optional.empty(); 11 | private List items = List.of(); 12 | private ShippingAddressRequest shippingAddress; 13 | private String remark; 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/domain/aggregate/OrderItem.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.domain.aggregate; 2 | 3 | import lombok.Builder; 4 | import lombok.Getter; 5 | import org.ddd.helper.As; 6 | 7 | import java.util.List; 8 | 9 | @Builder 10 | @Getter 11 | public class OrderItem { 12 | private Integer id; 13 | private String name; 14 | private String skuId; 15 | private Integer price; 16 | private As> itemFields; 17 | private String remark; 18 | 19 | public void updateRemark(String remark) { 20 | this.remark = remark; 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/domain/factory/OrderFactory.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.domain.factory; 2 | 3 | import org.ddd.example.domain.aggregate.Order; 4 | import org.ddd.example.domain.aggregate.OrderItem; 5 | import org.ddd.example.domain.aggregate.ShippingAddress; 6 | 7 | import java.util.List; 8 | 9 | import static org.ddd.helper.Suppliers.self; 10 | 11 | public interface OrderFactory { 12 | default Order crateOrder(String no) { 13 | return new Order(no, self(getOrderItems()), self(getShippingAddress())); 14 | } 15 | List getOrderItems(); 16 | ShippingAddress getShippingAddress(); 17 | } 18 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/application/PlaceOrderService.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.application; 2 | 3 | import org.ddd.example.application.data.request.OrderRequest; 4 | import org.ddd.example.application.data.response.OrderResponse; 5 | import org.ddd.example.application.factory.OrderFactoryImpl; 6 | import org.ddd.example.domain.aggregate.Order; 7 | import org.ddd.example.domain.repository.OrderRepository; 8 | 9 | public class PlaceOrderService { 10 | 11 | private OrderRepository orderRepository; 12 | 13 | public OrderResponse placeOrder(OrderRequest orderRequest) { 14 | Order order = OrderFactoryImpl.of(orderRequest).crateOrder(); 15 | return toResponse(orderRepository.save(order)); 16 | } 17 | 18 | public OrderResponse updateRemark(String orderNo, String remark) { 19 | Order order = orderRepository.get(orderNo); 20 | order.replaceRemark(remark); 21 | return toResponse(orderRepository.save(order)); 22 | } 23 | 24 | 25 | public OrderResponse updateRemark(String orderNo, Integer itemId, String remark) { 26 | Order order = orderRepository.get(orderNo); 27 | order.replaceRemark(itemId, remark); 28 | return toResponse(orderRepository.save(order)); 29 | } 30 | 31 | private OrderResponse toResponse(Order crateOrder) { 32 | return null; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.ddd.helper 8 | ddd-aggregate-helper 9 | 1.0-SNAPSHOT 10 | 11 | 12 | org.junit.jupiter 13 | junit-jupiter 14 | 5.8.2 15 | test 16 | 17 | 18 | org.projectlombok 19 | lombok 20 | RELEASE 21 | test 22 | 23 | 24 | org.mockito 25 | mockito-junit-jupiter 26 | 4.3.1 27 | test 28 | 29 | 30 | 31 | 32 | 11 33 | 11 34 | 35 | 36 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/domain/aggregate/Order.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.domain.aggregate; 2 | 3 | import lombok.Getter; 4 | import org.ddd.helper.As; 5 | 6 | import java.util.List; 7 | 8 | 9 | @Getter 10 | public class Order { 11 | public Order(String no, As> items, As shippingAddress) { 12 | this.no = no; 13 | this.totalPrice = items.get().stream().mapToInt(OrderItem::getPrice).sum(); 14 | this.items = items; 15 | this.shippingAddress = shippingAddress; 16 | } 17 | 18 | public Order(Integer id, String no, Integer totalPrice, As> items, As shippingAddress) { 19 | this.id = id; 20 | this.no = no; 21 | this.totalPrice = totalPrice; 22 | this.items = items; 23 | this.shippingAddress = shippingAddress; 24 | } 25 | 26 | private Integer id; 27 | private String no; 28 | private Integer totalPrice; 29 | private As> items; 30 | private As shippingAddress; 31 | private String remark; 32 | 33 | public void replaceRemark(String remark) { 34 | this.remark = remark; 35 | // log update 36 | } 37 | 38 | public void replaceRemark(Integer itemId, String remark) { 39 | this.getItems().get().stream() 40 | .filter(item -> item.getId().equals(itemId)) 41 | .findFirst().ifPresent(item -> item.updateRemark(remark)); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/ddd/helper/Suppliers.java: -------------------------------------------------------------------------------- 1 | package org.ddd.helper; 2 | 3 | import java.util.concurrent.atomic.AtomicReference; 4 | import java.util.function.Supplier; 5 | 6 | import static java.util.Objects.requireNonNull; 7 | 8 | public class Suppliers { 9 | 10 | public static As awareMemoize(Supplier supplier) { 11 | return new AwareMemoizeSupplier<>(supplier); 12 | } 13 | 14 | public static As self(T self) { 15 | return new SelfSupplier<>(self); 16 | } 17 | private static class AwareMemoizeSupplier implements As { 18 | private final AtomicReference value = new AtomicReference<>(); 19 | private final Supplier supplier; 20 | private boolean callInnerGet = false; 21 | 22 | AwareMemoizeSupplier(Supplier supplier) { 23 | requireNonNull(supplier); 24 | this.supplier = supplier; 25 | } 26 | 27 | @Override 28 | public boolean isHere() { 29 | return callInnerGet; 30 | } 31 | 32 | @Override 33 | public T get() { 34 | T val = value.get(); 35 | if (val == null) { 36 | synchronized (value) { 37 | val = value.get(); 38 | if (val == null) { 39 | val = supplier.get(); 40 | callInnerGet = true; 41 | value.set(val); 42 | } 43 | } 44 | } 45 | return val; 46 | } 47 | } 48 | 49 | private static class SelfSupplier implements As { 50 | private final T self; 51 | 52 | SelfSupplier(T self) { 53 | requireNonNull(self); 54 | this.self = self; 55 | } 56 | 57 | @Override 58 | public boolean isHere() { 59 | return true; 60 | } 61 | 62 | @Override 63 | public T get() { 64 | return self; 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/helper/SuppliersTest.java: -------------------------------------------------------------------------------- 1 | package org.ddd.helper; 2 | 3 | import org.junit.jupiter.api.Nested; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import java.time.LocalDateTime; 7 | 8 | import static org.junit.jupiter.api.Assertions.*; 9 | 10 | class SuppliersTest { 11 | @Nested 12 | class SelfSupplierTest { 13 | @Test 14 | void should_return_true_when_call_is_here() { 15 | As selfSupplier = Suppliers.self(new Object()); 16 | 17 | assertTrue(selfSupplier.isHere()); 18 | } 19 | 20 | @Test 21 | void should_return_self_when_get() { 22 | Object whatever = new Object(); 23 | As selfSupplier = Suppliers.self(whatever); 24 | 25 | assertEquals(whatever, selfSupplier.get()); 26 | } 27 | } 28 | 29 | @Nested 30 | class AwareMemoizeSupplierTest { 31 | @Test 32 | void should_return_false_when_call_is_here_if_not_get() { 33 | As awareMemoize = Suppliers.awareMemoize(Object::new); 34 | 35 | assertFalse(awareMemoize.isHere()); 36 | } 37 | 38 | @Test 39 | void should_return_ture_when_call_is_here_after_get() { 40 | As awareMemoize = Suppliers.awareMemoize(Object::new); 41 | awareMemoize.get(); 42 | 43 | assertTrue(awareMemoize.isHere()); 44 | } 45 | 46 | @Test 47 | void should_return_supplier_type_when_get() { 48 | As awareMemoize = Suppliers.awareMemoize(LocalDateTime::now); 49 | 50 | assertTrue(awareMemoize.get() instanceof LocalDateTime); 51 | } 52 | 53 | @Test 54 | void should_return_the_same_object_when_get_2_times() { 55 | As awareMemoize = Suppliers.awareMemoize(LocalDateTime::now); 56 | 57 | Object get1 = awareMemoize.get(); 58 | Object get2 = awareMemoize.get(); 59 | 60 | assertSame(get1, get2); 61 | } 62 | } 63 | } -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/application/factory/OrderFactoryImpl.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.application.factory; 2 | 3 | import org.ddd.example.application.data.request.ItemFieldRequest; 4 | import org.ddd.example.application.data.request.OrderItemRequest; 5 | import org.ddd.example.application.data.request.OrderRequest; 6 | import org.ddd.example.application.data.request.ShippingAddressRequest; 7 | import org.ddd.example.domain.aggregate.ItemField; 8 | import org.ddd.example.domain.aggregate.Order; 9 | import org.ddd.example.domain.aggregate.OrderItem; 10 | import org.ddd.example.domain.aggregate.ShippingAddress; 11 | import org.ddd.example.domain.factory.OrderFactory; 12 | import org.ddd.helper.Suppliers; 13 | 14 | import java.util.List; 15 | import java.util.UUID; 16 | import java.util.stream.Collectors; 17 | 18 | public class OrderFactoryImpl implements OrderFactory { 19 | 20 | private final OrderRequest orderDTO; 21 | 22 | private OrderFactoryImpl(OrderRequest orderRequest) { 23 | this.orderDTO = orderRequest; 24 | } 25 | 26 | public static OrderFactoryImpl of(OrderRequest orderDTO) { 27 | return new OrderFactoryImpl(orderDTO); 28 | } 29 | 30 | public Order crateOrder() { 31 | return crateOrder(orderDTO.getNo().orElseGet(this::genOrderNo)); 32 | } 33 | 34 | private String genOrderNo() { 35 | return UUID.randomUUID().toString(); 36 | } 37 | 38 | @Override 39 | public List getOrderItems() { 40 | return orderDTO.getItems().stream().map(this::toItem).collect(Collectors.toList()); 41 | } 42 | 43 | private OrderItem toItem(OrderItemRequest orderItemRequest) { 44 | return OrderItem.builder().name(orderItemRequest.getName()) 45 | .price(orderItemRequest.getPrice()) 46 | .skuId(orderItemRequest.getSkuId()) 47 | .itemFields(Suppliers.self(toDO(orderItemRequest.getFields()))) 48 | .build(); 49 | } 50 | 51 | private List toDO(List fields) { 52 | return fields.stream().map(filed -> ItemField.builder() 53 | .key(filed.getKey()).type(filed.getType()).value(filed.getValue()).build()) 54 | .collect(Collectors.toList()); 55 | } 56 | 57 | @Override 58 | public ShippingAddress getShippingAddress() { 59 | ShippingAddressRequest dto = orderDTO.getShippingAddress(); 60 | return ShippingAddress.builder() 61 | .address(dto.getAddress()) 62 | .phone(dto.getPhone()) 63 | .receiverName(dto.getReceiverName()) 64 | .build(); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/inforstructure/repository/OrderRepositoryImpl.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.inforstructure.repository; 2 | 3 | import org.ddd.example.domain.aggregate.ItemField; 4 | import org.ddd.example.domain.aggregate.Order; 5 | import org.ddd.example.domain.aggregate.OrderItem; 6 | import org.ddd.example.domain.aggregate.ShippingAddress; 7 | import org.ddd.example.domain.repository.OrderRepository; 8 | import org.ddd.example.inforstructure.data.ItemFieldPO; 9 | import org.ddd.example.inforstructure.data.OrderItemPO; 10 | import org.ddd.example.inforstructure.data.OrderPO; 11 | import org.ddd.example.inforstructure.mapper.ItemFieldMapper; 12 | import org.ddd.example.inforstructure.mapper.OrderItemMapper; 13 | import org.ddd.example.inforstructure.mapper.OrderMapper; 14 | import org.ddd.helper.Suppliers; 15 | 16 | import java.util.List; 17 | import java.util.stream.Collectors; 18 | 19 | public class OrderRepositoryImpl implements OrderRepository { 20 | 21 | private OrderMapper orderMapper; 22 | private OrderItemMapper orderItemMapper; 23 | private ItemFieldMapper itemFieldMapper; 24 | 25 | @Override 26 | public Order save(Order order) { 27 | OrderPO orderPO = toPO(order); 28 | orderMapper.save(orderPO); 29 | if (order.getItems().isHere()) { 30 | OrderItemPO[] items = order.getItems().get().stream().map(this::toPO).toArray(OrderItemPO[]::new); 31 | orderItemMapper.save(items); 32 | for (OrderItem item : order.getItems().get()) { 33 | if (item.getItemFields().isHere() && !item.getItemFields().get().isEmpty()) { 34 | ItemFieldPO[] fields = item.getItemFields().get().stream().map(this::toPO).toArray(ItemFieldPO[]::new); 35 | itemFieldMapper.save(fields); 36 | } 37 | } 38 | } 39 | return get(order.getNo()); 40 | } 41 | 42 | private ItemFieldPO toPO(ItemField itemField) { 43 | return new ItemFieldPO(); 44 | } 45 | 46 | private OrderItemPO toPO(OrderItem orderItem) { 47 | return new OrderItemPO(); 48 | } 49 | 50 | private OrderPO toPO(Order order) { 51 | return new OrderPO(); 52 | } 53 | 54 | @Override 55 | public Order get(String orderNo) { 56 | OrderPO orderPO = orderMapper.get(orderNo); 57 | if (orderPO == null) { 58 | throw new RuntimeException(String.format("order not found orderNo:%s", orderNo)); 59 | } 60 | Integer orderId = orderPO.getId(); 61 | return new Order(orderId, orderPO.getNo(), orderPO.getId(), 62 | Suppliers.awareMemoize(() -> toDOs(orderItemMapper.findBy(orderId))), 63 | Suppliers.self(toSippingAddressDO(orderPO))); 64 | } 65 | 66 | private ShippingAddress toSippingAddressDO(OrderPO orderPO) { 67 | return ShippingAddress.builder() 68 | .address(orderPO.getAddress()) 69 | .receiverName(orderPO.getReceiverName()) 70 | .phone(orderPO.getPhone()) 71 | .build(); 72 | } 73 | 74 | private List toDOs(List itemPOS) { 75 | return itemPOS.stream().map(itemPO -> { 76 | Integer itemId = itemPO.getId(); 77 | return OrderItem.builder().id(itemId) 78 | .itemFields(Suppliers.awareMemoize(() -> this.toItemFileds(ItemFieldMapper.findBy(itemId)))) 79 | .build(); 80 | }).collect(Collectors.toList()); 81 | } 82 | 83 | private List toItemFileds(List itemFieldPOS) { 84 | return null; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # 领域模型太复杂怎么破? 3 | 4 | ## 背景 5 | 6 | 按照 DDD 的设计思想,调用方仅能操作 Aggregate Root,而不能单独针对某个非 Aggregate Root 的 Entity 直接操作。但有时候业务模型就是很复杂,如果拆分成多个 Aggregate,相互之间的依赖会让业务逻辑的实现变得更复杂。 7 | 8 | ## 主流方案 9 | 10 | 有什么办法削弱复杂的 Aggregate 产生的负面影响呢?常见的主流方案是 **Change-Tracking** 变化追踪,如果能知道哪些值变化了,就只需要更新有变化的值。就不会出现只更新了一个状态值,整个 Aggregate 相关的数据模型都更新了一遍的尴尬场景了。常见的实现方式有 11 | 12 | ##### 1、基于Snapshot的方案: 13 | 14 | 当数据从DB里取出来后,在内存中保存一份snapshot,然后在数据写入时和snapshot比较。常见的实现如Hibernate。 15 | 16 | ##### 2、基于Proxy的方案: 17 | 18 | 当数据从DB里取出来后,通过weaving的方式将所有setter都增加一个切面来判断setter是否被调用以及值是否变更,如果变更则标记为Dirty。在保存时根据Dirty判断是否需要更新。常见的实现如Entity Framework。 19 | 20 | 21 | 22 | ## 新的实践 23 | 24 | 现实中的 Aggregate 虽然复杂,但子实体的更新并不频繁,大概率是聚合的状态变更,典型的例子就是电商的交易。大部分场景只需要用到交易主表的信息,或只需要更新交易的状态,但是构造 Aggregate 时会把所有的非 Aggregate Root 的 Entity 也构造出来。所以主流方案用到现在的交易系统不仅实现成本较高,还不能解决所有的痛点。但受到上面方案的启发,想到了一种更轻量的方案。 25 | 26 | #### LazyRead&Tracking 27 | 28 | 主要的思路就是在构造 Aggregate 时,并不直接构造所有的 Entity ,而只构造主 Entity 并构造其他 Entity 的改造方法(🚫禁止套娃)。然后在持久化时只处理正在构造过的实体。那么问题来了。 29 | 30 | - 如何实现在用的时候才构造呢? 31 | - 重复读取的时候怎么保证只构造一次呢? 32 | - 持久化的时候怎么才能感知到哪些实体是构造过的呢? 33 | - 新创建的实体怎么在持久化时正确处理呢? 34 | 35 | 答案就是 **AwareSupplier**(现代码已简化为 **As**)。 36 | 37 | ```Java 38 | public interface AwareSupplier extends Supplier { 39 | boolean isHere(); 40 | } 41 | ``` 42 | 43 | `AwareSupplier` 继承自 `Supplier`。相比 `Supplier` 多定义了一个方法 `isHere()` 用于表示调用 `get()` 可以获取的 `T` 的实例是否已经构造好了。 44 | 45 | 光看 `AwareSupplier` 这个接口还得不到完整的答案,我们继续看一下这个接口的实现。 46 | 47 | 我定义了两个实现类 `SelfSupplier` 和 `AwareMemoizeSupplier`,都定义在 `Suppliers` 内部。 48 | 49 | ```Java 50 | private static class SelfSupplier implements AwareSupplier { 51 | private final T goods; 52 | 53 | SelfSupplier(@NotNull T goods) { 54 | this.goods = goods; 55 | } 56 | 57 | @Override 58 | public boolean isGoodsHere() { 59 | return true; 60 | } 61 | 62 | @Override 63 | public T get() { 64 | return goods; 65 | } 66 | } 67 | ``` 68 | 69 | 可以看到 `SelfSupplier` 的 `isHere()` 方法永远返回 `true`,而 `get()` 方法返回实例是在构造 `SelfSupplier`时直接传入的。很明显,这样的实现是用在构造新创建的实体时。 70 | 71 | ---- 72 | 73 | ```java 74 | private static class AwareMemoizeSupplier implements AwareSupplier { 75 | private final AtomicReference value = new AtomicReference<>(); 76 | private final Supplier supplier; 77 | private boolean callInnerGet = false; 78 | 79 | AwareMemoizeSupplier(@NotNull Supplier supplier) { 80 | this.supplier = supplier; 81 | } 82 | 83 | @Override 84 | public boolean isHere() { 85 | return callInnerGet; 86 | } 87 | 88 | @Override 89 | public T get() { 90 | T val = value.get(); 91 | if (val == null) { 92 | synchronized (value) { 93 | val = value.get(); 94 | if (val == null) { 95 | val = supplier.get(); 96 | callInnerGet = true; 97 | value.set(val); 98 | } 99 | } 100 | } 101 | return val; 102 | } 103 | } 104 | ``` 105 | 106 | 与`SelfSupplier` 不同的是, `AwareMemoizeSupplier` 的构造函数的入参是 `Supplier` 并且多了两个私有变量,一个用来标记是否调用过`Supplier` 的 `get()` 方法,一个用来缓存 `get()` 方法返回的结果。这样就可以解决上面的疑问了。在调用 `AwareMemoizeSupplier` 的 `get()` 方法时,会先尝试从缓存中获取,获取不到才真正调用 `Supplier` 的 `get()` 方法去获取,并且会就标记变量设置为 `true`。 107 | 这里还加了 `synchronized` 主要考虑到通用性,如果确定不会有线程安全问题可以去掉。 108 | 109 | #### 命名的来由 110 | 111 | `AwareSupplier` 是想表达具有感知能力的 `Supplier`。 112 | 113 | `AwareMemoizeSupplier`是想表达具有感知能力且拥有记忆的 `Supplier`。 114 | 115 | `SelfSupplier`是想表达一种特殊的、可以提供自我获取能力的 `Supplier`。 116 | 117 | 如果你想到更好的命名,请及时告诉我,或者直接提MR。 -------------------------------------------------------------------------------- /src/test/java/org/ddd/example/test/OrderServiceTest.java: -------------------------------------------------------------------------------- 1 | package org.ddd.example.test; 2 | 3 | import org.ddd.example.application.PlaceOrderService; 4 | import org.ddd.example.application.data.request.ItemFieldRequest; 5 | import org.ddd.example.application.data.request.OrderItemRequest; 6 | import org.ddd.example.application.data.request.OrderRequest; 7 | import org.ddd.example.application.data.request.ShippingAddressRequest; 8 | import org.ddd.example.domain.repository.OrderRepository; 9 | import org.ddd.example.inforstructure.data.ItemFieldPO; 10 | import org.ddd.example.inforstructure.data.OrderItemPO; 11 | import org.ddd.example.inforstructure.data.OrderPO; 12 | import org.ddd.example.inforstructure.mapper.ItemFieldMapper; 13 | import org.ddd.example.inforstructure.mapper.OrderItemMapper; 14 | import org.ddd.example.inforstructure.mapper.OrderMapper; 15 | import org.ddd.example.inforstructure.repository.OrderRepositoryImpl; 16 | import org.junit.jupiter.api.Test; 17 | import org.junit.jupiter.api.extension.ExtendWith; 18 | import org.mockito.InjectMocks; 19 | import org.mockito.Mock; 20 | import org.mockito.junit.jupiter.MockitoExtension; 21 | 22 | import java.util.List; 23 | import java.util.Optional; 24 | 25 | import static org.mockito.ArgumentMatchers.any; 26 | import static org.mockito.Mockito.*; 27 | 28 | @ExtendWith(MockitoExtension.class) 29 | class OrderServiceTest { 30 | 31 | public static final String ORDER_NO = "O-10000000001"; 32 | @InjectMocks 33 | private PlaceOrderService orderController; 34 | @InjectMocks 35 | private OrderRepository orderRepository = spy(OrderRepositoryImpl.class); 36 | @Mock 37 | private OrderMapper orderMapper; 38 | @Mock 39 | private OrderItemMapper orderItemMapper; 40 | @Mock 41 | private ItemFieldMapper itemFieldMapper; 42 | 43 | 44 | @Test 45 | void should_save_all_entity_when_create_new_aggregation() { 46 | when(orderMapper.save(any(OrderPO.class))).thenReturn(new OrderPO()); 47 | when(orderItemMapper.save(any(OrderItemPO[].class))).thenReturn(new OrderItemPO[0]); 48 | when(itemFieldMapper.save(any(ItemFieldPO[].class))).thenReturn(new ItemFieldPO[0]); 49 | when(orderMapper.get(any(String.class))).thenReturn(new OrderPO()); 50 | 51 | orderController.placeOrder(buildOrderRequest()); 52 | 53 | verify(orderMapper).save(any(OrderPO.class)); 54 | verify(orderItemMapper).save(any(OrderItemPO[].class)); 55 | verify(itemFieldMapper).save(any(ItemFieldPO[].class)); 56 | } 57 | 58 | @Test 59 | void should_save_order_only_when_update_remark() { 60 | OrderPO orderPO = buildOrderPO(); 61 | when(orderMapper.get(eq(ORDER_NO))).thenReturn(orderPO, orderPO); 62 | when(orderMapper.save(any(OrderPO.class))).thenReturn(new OrderPO()); 63 | 64 | orderController.updateRemark(ORDER_NO, "尽快发货"); 65 | 66 | verify(orderMapper, times(1)).save(any(OrderPO.class)); 67 | verify(orderItemMapper, times(0)).save(any(OrderItemPO[].class)); 68 | verify(itemFieldMapper, times(0)).save(any(ItemFieldPO[].class)); 69 | } 70 | 71 | @Test 72 | void should_save_order_item_when_update_item_remark() { 73 | OrderPO orderPO = buildOrderPO(); 74 | when(orderMapper.get(eq(ORDER_NO))).thenReturn(orderPO, orderPO); 75 | when(orderMapper.save(any(OrderPO.class))).thenReturn(new OrderPO()); 76 | 77 | orderController.updateRemark(ORDER_NO, 1, "要今年生产的"); 78 | 79 | verify(orderMapper, times(1)).save(any(OrderPO.class)); 80 | verify(orderItemMapper, times(1)).save(any(OrderItemPO[].class)); 81 | verify(itemFieldMapper, times(0)).save(any(ItemFieldPO[].class)); 82 | } 83 | 84 | private OrderPO buildOrderPO() { 85 | OrderPO orderPO = new OrderPO(); 86 | orderPO.setNo(ORDER_NO); 87 | return orderPO; 88 | } 89 | 90 | private OrderRequest buildOrderRequest() { 91 | OrderRequest orderRequest = new OrderRequest(); 92 | orderRequest.setNo(Optional.of(ORDER_NO)); 93 | 94 | OrderItemRequest item1 = new OrderItemRequest(); 95 | item1.setName("润喉糖"); 96 | item1.setSkuId("R-1"); 97 | item1.setPrice(10); 98 | 99 | OrderItemRequest item2 = new OrderItemRequest(); 100 | item2.setName("康泰克"); 101 | item2.setSkuId("KTK-2"); 102 | item2.setPrice(20); 103 | ItemFieldRequest itemField = new ItemFieldRequest(); 104 | itemField.setKey("身份证好"); 105 | itemField.setType("身份证"); 106 | itemField.setValue("1228471237849127XX"); 107 | item2.setFields(List.of(itemField)); 108 | 109 | orderRequest.setItems(List.of(item1, item2)); 110 | 111 | ShippingAddressRequest shippingAddress = new ShippingAddressRequest(); 112 | shippingAddress.setAddress("xxx"); 113 | shippingAddress.setPhone("232132199278"); 114 | shippingAddress.setReceiverName("xxx"); 115 | orderRequest.setShippingAddress(shippingAddress); 116 | return orderRequest; 117 | } 118 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------