組合模式在商品分類列表中的應用

在全部的樹形結構中最適合的設計模式就是組合模式,咱們看看經常使用商品分類中如何使用。設計模式

先定義一個樹形結構的商品接口ide

public interface TreeProduct {
    List<TreeProduct> allProducts();
    boolean addProduct(TreeProduct product);
    boolean addProducts(List<TreeProduct> products);
    boolean removeProduct(TreeProduct product);
}

咱們來定義一個商品分類的實現類this

@NoArgsConstructor
@ToString
public class TypeProduct implements TreeProduct {
    @Getter
    @Setter
    private Integer id;
    @Getter
    @Setter
    private String name;
    @Getter
    private List<TreeProduct> treeProducts = new CopyOnWriteArrayList<>();
    public TypeProduct(Integer id,String name) {
        this.id = id;
        this.name = name;
    }
    @Override
    public List<TreeProduct> allProducts() {
        return this.treeProducts;
    }

    @Override
    public boolean addProduct(TreeProduct product) {
        return treeProducts.add(product);
    }

    @Override
    public boolean removeProduct(TreeProduct product) {
        return treeProducts.remove(product);
    }

    @Override
    public boolean addProducts(List<TreeProduct> products) {
        return treeProducts.addAll(products);
    }
}

而後定義一個商品類spa

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Product implements TreeProduct {
    private Integer id;
    private String name;
    private String model;
    private BigDecimal price;

    @Override
    public List<TreeProduct> allProducts() {
        return Arrays.asList(this);
    }

    @Override
    public boolean addProduct(TreeProduct product) {
        throw new RuntimeException("不支持此方法");
    }

    @Override
    public boolean removeProduct(TreeProduct product) {
        throw new RuntimeException("不支持此方法");
    }

    @Override
    public boolean addProducts(List<TreeProduct> products) {
        throw new RuntimeException("不支持此方法");
    }
}

最後是main方法,固然你能夠在Web的系統去改造這個模式設計

public class ProductMain {
    public static void main(String[] args) {
        TreeProduct root = new TypeProduct(100,"根目錄");
        TreeProduct type1 = new TypeProduct(200,"可樂");
        TreeProduct type2 = new TypeProduct(300,"咖啡");
        List<TreeProduct> types1 = new ArrayList<>();
        types1.add(type1);
        types1.add(type2);
        TreeProduct product1 = new Product(1,"可口可樂","500ml",new BigDecimal(3));
        TreeProduct product2 = new Product(2,"雀巢咖啡","600ml",new BigDecimal(6));
        root.addProducts(types1);
        type1.addProduct(product1);
        type2.addProduct(product2);
        System.out.println(JSON.toJSONString(root));
    }
}

運行結果:接口

{"id":100,"name":"根目錄","takeCareProducts":[{"id":200,"name":"可樂","takeCareProducts":[{"id":1,"model":"500ml","name":"可口可樂","price":3}]},{"id":300,"name":"咖啡","takeCareProducts":[{"id":2,"model":"600ml","name":"雀巢咖啡","price":6}]}]}ci

相關文章
相關標籤/搜索