深入理解Java设计模式-外观模式

什么是外观模式

外观模式:也叫门面模式,隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。

它向现有的系统添加一个接口,用这一个接口来隐藏实际的系统的复杂性。

使用外观模式,他外部看起来就是一个接口,其实他的内部有很多复杂的接口已经被实现

外观模式例子

用户注册完之后,需要调用阿里短信接口、邮件接口、微信推送接口。

  1. 创建阿里短信接口
package com.lijie;

//阿里短信消息
public interface AliSmsService {
	void sendSms();
}
package com.lijie;

public class AliSmsServiceImpl implements AliSmsService {

    public void sendSms() {
        System.out.println("阿里短信消息");
    }

}
  1. 创建邮件接口
package com.lijie;

//发送邮件消息
public interface EamilSmsService {
	void sendSms();
}
package com.lijie;

public class EamilSmsServiceImpl implements   EamilSmsService{
	public void sendSms() {
		System.out.println("发送邮件消息");
	}
}
  1. 创建微信推送接口
package com.lijie;

//微信消息推送
public interface WeiXinSmsService {
   void sendSms();
}
package com.lijie;

public class WeiXinSmsServiceImpl implements  WeiXinSmsService {
    public void sendSms() {
        System.out.println("发送微信消息推送");
    }
}
  1. 创建门面(门面看起来很简单使用,复杂的东西以及被门面给封装好了)
package com.lijie;

public class Computer {
	AliSmsService aliSmsService;
	EamilSmsService eamilSmsService;
	WeiXinSmsService weiXinSmsService;

	public Computer() {
		aliSmsService = new AliSmsServiceImpl();
		eamilSmsService = new EamilSmsServiceImpl();
		weiXinSmsService = new WeiXinSmsServiceImpl();
	}

	//只需要调用它
	public void sendMsg() {
		aliSmsService.sendSms();
		eamilSmsService.sendSms();
		weiXinSmsService.sendSms();
	}
}
  1. 启动测试
package com.lijie;

public class Client {

    public static void main(String[] args) {
        //普通模式需要这样
        AliSmsService aliSmsService = new AliSmsServiceImpl();
        EamilSmsService eamilSmsService = new EamilSmsServiceImpl();
        WeiXinSmsService weiXinSmsService = new WeiXinSmsServiceImpl();
        aliSmsService.sendSms();
        eamilSmsService.sendSms();
        weiXinSmsService.sendSms();

        //利用外观模式简化方法
        new Computer().sendMsg();
    }
}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值