类图关系如下:
示例代码:
public interface IMaterial {
void pack();
}
public class PaperBag implements IMaterial {
@Override
public void pack() {
System.out.println("使用纸质包装盒打包----");
}
}
public class PlasticBag implements IMaterial {
@Override
public void pack() {
System.out.println("使用塑料材质包装----");
}
}
public abstract class BagAbstract {
private IMaterial material; //持有可扩展接口角色引用
public BagAbstract(IMaterial material) {
this.material = material;
}
public abstract void pick();
}
public class BigBag extends BagAbstract {
public BigBag(IMaterial material) {
super(material);
}
@Override
public void pick() {
System.out.println("使用大号袋子进行采摘");
}
}
public class MidBag extends BagAbstract {
public MidBag(IMaterial material) {
super(material);
}
@Override
public void pick() {
System.out.println("使用中号袋子进行采摘");
}
}
public class SmallBag extends BagAbstract {
public SmallBag(IMaterial material) {
super(material);
}
@Override
public void pick() {
System.out.println("使用小号袋子进行采摘");
}
}
public class Test {
public static void main(String[] args) {
IMaterial material = new PaperBag(); //可以任意选择包装材质(材质可以扩展)
BagAbstract big = new BigBag(material);//可以选择包装的规格大小
material.pack();
big.pick();
}
}