命令模式:用构造函数将 命令实现者 传递给 调用者。
例如下面 小贩进货
设计模式,一定要敲代码理解
命令抽象
/**
*文具
* */
public interface Stationery {
void make();
}
命令实现类
public class Pencil implements Stationery{
private Producer producer;
public Pencil(Producer producer) {
this.producer = producer;
}
@Override
public void make() {
producer.doProduce();
}
}
public class WatercolorPen implements Stationery {
private Producer producer;
public WatercolorPen(Producer producer) {
this.producer = producer;
}
@Override
public void make() {
producer.doProduce();
}
}
实现者抽象
public interface Producer {
void doProduce();
}
实现者具体
public class ChenGuang implements Producer {
@Override
public void doProduce() {
System.out.println("晨光品牌——————值得信赖");
}
}
public class Deil implements Producer {
@Override
public void doProduce() {
System.out.println("得力品牌——————值得信赖");
}
}
调用者
public class Hawker {
private List<Stationery> stationeries=new ArrayList<>();
public void stock(Stationery item){
stationeries.add(item);
}
public void all(){
for (Stationery item: stationeries){
item.make();
}
}
}
测试与结果
public class Main {
public static void main(String[] args) {
Stationery s1=new Pencil(new Deil());
Stationery s2=new WatercolorPen(new ChenGuang());
//小贩去进货
Hawker hawker=new Hawker();
hawker.stock(s1);
hawker.stock(s2);
//查看商品
hawker.all();
}
}
得力品牌——————值得信赖
晨光品牌——————值得信赖
总结
核心要素 调用者, 命令, 命令实现者。 调用者调用命令,其实是委托给命令实现者,满足单一职责,便于扩展。