小明在追小红,不停的在写情书。写信呢有四步,1是写信的内容,2写好信封,3把信装入信封,4将信寄出。过去这些步骤都是他自己完成。现在呢?他只要递给邮局邮局就帮他寄出。这个逻辑怎么实现?
定义一个写信过程的接口
public interface ILetterProcess {
//首先写信的内容
void writeContext(String context);
//其次写信封
void fillEnvelope(String address);
//把信放入信封
void letterIntoEnvelope();
//寄信
void sendLetter();
}
实现这个接口
public class LetterProcess implements ILetterProcess {
public void writeContext(String context) {
System.out.println("信的内容是:"+context);
}
public void fillEnvelope(String address) {
System.out.println("寄给"+address);
}
public void letterIntoEnvelope() {
System.out.println("把信放到信封");
}
public void sendLetter() {
System.out.println("将信寄出");
}
}
有个邮局充当门面,替他完成这些方法。门面类应该固定不能经常变动,实现了写信过程类与高层场景类的解耦。
public class PostOffice {
private ILetterProcess letterProcess = new LetterProcess();
public void sendLetter(String contest, String address) {
letterProcess.writeContext(contest);
letterProcess.fillE
nvelope(address);
letterProcess.letterIntoEnvelope();
letterProcess.sendLetter();
}
}
最后看看场景
public class Client {
public static void main(String[] args) {
PostOffice postOffice = new PostOffice();
postOffice.sendLetter("小红小红我爱你","小红的家里");
}
}
运行结果:
信的内容是:小红小红我爱你
寄给小红的家里
把信放到信封
将信寄出