设计模式之门面模式

小明在追小红,不停的在写情书。写信呢有四步,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("小红小红我爱你","小红的家里");
    }
}

运行结果:
信的内容是:小红小红我爱你
寄给小红的家里
把信放到信封
将信寄出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值