一、定义
雇工模式也叫做仆人模式(ServantDesignPattern),是行为模式的一种,其意图是:
为一组类提供通用的功能,而不需要类实现这些功能,它是命令模式的一种扩展。
二、类图
1. IServiced 被服务者
定义“一组类”所具有的通用功能。
public interface IServiced {
// 具有的特质或功能
public void serviced();
}
2. ConcreteServiced 具体的被服务对象
实现 IServiced,并完成具体逻辑。
public class Serviced1 implements IServiced {
public void serviced() {
}
}
public class Serviced2 implements IServiced {
public void serviced() {
}
}
3. Servant 仆人类
public class Servant {
// 服务内容
public void service(IServiced service) {
service.serviced();
}
}
4. Client 场景
public class Client {
public static void main(String[] args) {
Servant servant = new Servant();
servant.service(new Serviced1());
servant.service(new Serviced2());
}
}
三、实例分析
日常开发中我们可能已经接触了雇工模式,只是没有把它抽取出来。雇工模式是命令模式的简化版本,它可能更符合我们实际的需要,也更容易引入到开发场景中。
例如有一个富豪,他雇佣了一个仆人,家里的清洁工作都是仆人来完成。比如说花园和厨房,都有一个共同特性,就是“可清理的”,它们都有一个共同方法,就是“被清理”。
1. ICleanable 接口
// 被服务者
public interface ICleanable {
void cleaned();
}
2. 具体的实现
public class Garden implements ICleanable {
public void cleaned() {
System.out.println("花园被清理干净");
}
}
public class Kitchen implements ICleanable {
public void cleaned() {
System.out.println("厨房被清理干净");
}
}
3. 仆人类
public class Cleaner {
public void clean(ICleanable cleanable) {
cleanable.cleaned();
}
}
4. 模拟一个场景
public class Client {
public static void main(String[] args) {
Cleaner cleaner = new Cleaner();
cleaner.clean(new Garden());
cleaner.clean(new Kitchen());
}
}
5. 运行结果为
花园被清理干净
厨房被清理干净
查看更多:设计模式分类以及六大设计原则