组合模式在商品分类列表中的应用 顶

2019-08-20 10:32:59 浏览数 (1)

在所有的树形结构中最适合的设计模式就是组合模式,我们看看常用商品分类中如何使用。

先定义一个树形结构的商品接口

代码语言:javascript复制
public interface TreeProduct {
    List<TreeProduct> allProducts();
    boolean addProduct(TreeProduct product);
    boolean addProducts(List<TreeProduct> products);
    boolean removeProduct(TreeProduct product);
}

我们来定义一个商品分类的实现类

代码语言:javascript复制
@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);
    }
}

然后定义一个商品类

代码语言:javascript复制
@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的系统去改造这个模式

代码语言:javascript复制
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}]}]}

0 人点赞