本文翻译自:https://www.journaldev.com/1535/composite-design-pattern-in-java
Composite Design Pattern in Java
这种模式是基于具有共同行为的多个对象的存在,用于构建更大的对象。较大的对象仍然具有与最小对象相同的特征。
让我们用一个真实生活案例来解释:一个图表是用圆、直线、长方形等构成。当我们用颜料来画画的时候,相同的颜色会被重复使用,画图的过程是一个重复的过程,里面的一些操作是相同的;
复合模式由以下几个方面构成:
- Base Component:Base Component是所有对象的接口,它可以是一个抽象类或interface;
- Leaf : 定义了元素的行为,实现了Base Component,并与其他组件无引用关系;
- Composite : 由Leaf 构成,实现了Base Component中的操作方法;
接下来使用一个画画的例子来例证:
Base Component
复合模式的Base Component为Leaf和Composites 定义了一些普通的方法,我们可以创建一个Shape类,包含一个draw(String fillColor) 方法,其可以指定颜色;
Shape.java
package com.journaldev.design.composite;
public interface Shape {
public void draw(String fillColor);
}
Leaf Objects
Leaf实现了Base Component接口,它是Composite的构建区块,我们可以创建多个Leaf,比如Triangle、Circle;
Triangle.java
package com.journaldev.design.composite;
public class Triangle implements Shape {
@Override
public void draw(String fillColor) {
System.out.println("Drawing Triangle with color "+fillColor);
}
}
Circle.java
package com.journaldev.design.composite;
public class Circle implements Shape {
@Override
public void draw(String fillColor) {
System.out.println("Drawing Circle with color "+fillColor);
}
}
Composite object
Composite 包含了一组Leaf组件,所以在Composite 内部提供了一些add和delete方法来增加或删除Leaf组件,也可以提供remove all将所有Leaf删除。
Drawing.java
package com.journaldev.design.composite;
import java.util.ArrayList;
import java.util.List;
public class Drawing implements Shape{
//collection of Shapes
private List<Shape> shapes = new ArrayList<Shape>();
@Override
public void draw(String fillColor) {
for(Shape sh : shapes)
{
sh.draw(fillColor);
}
}
//adding shape to drawing
public void add(Shape s){
this.shapes.add(s);
}
//removing shape from drawing
public void remove(Shape s){
shapes.remove(s);
}
//removing all the shapes
public void clear(){
System.out.println("Clearing all the shapes from drawing");
this.shapes.clear();
}
}
Composite Design Pattern Client Program
然后对该模式进行测试:TestCompositePattern.java
package com.journaldev.design.test;
import com.journaldev.design.composite.Circle;
import com.journaldev.design.composite.Drawing;
import com.journaldev.design.composite.Shape;
import com.journaldev.design.composite.Triangle;
public class TestCompositePattern {
public static void main(String[] args) {
Shape tri = new Triangle();
Shape tri1 = new Triangle();
Shape cir = new Circle();
Drawing drawing = new Drawing();
drawing.add(tri1);
drawing.add(tri1);
drawing.add(cir);
drawing.draw("Red");
drawing.clear();
drawing.add(tri);
drawing.add(cir);
drawing.draw("Green");
}
}
输出:
Drawing Triangle with color Red
Drawing Triangle with color Red
Drawing Circle with color Red
Clearing all the shapes from drawing
Drawing Triangle with color Green
Drawing Circle with color Green