Java装饰者模式介绍+实际应用场景的案例 -- 柚子真好吃
一、装饰者模式简单介绍
- 穿衣服,蛋糕上加草莓,电脑安音响耳机,小卡片上画条哥。
- 简单来讲就是为某一个东西,装饰一些漂亮的饰品,增强一些事务。
- 为一个现有的类,在不改变原代码的情况下,修饰或添加新功能。
- 也可以将装饰者模式理解为功能模块的分割,类似于分布式理解。
二、业务介绍
- 有一个用户名和密码登陆的功能,现在记录登陆的日志,同时添加一个微信登陆功能。
- 如果不用装饰者模式也是可以完成的,我们只需重新写一个接口定义 微信登陆。同时在每次登陆成功后添加记录日志功能。
- 弊端:如果不需要该功能?后期维护的成本特别大,代码都写到了一个耦合度特别大。
- 在采用装饰者模式后,对于功能的修改或添加,我们将采取模块化管理,如果想要实现这个功能那么仅一行代码即可开启,如果不需要那么也是一行代码来关闭。这样也符合了分布式的理念。
三、代码实现
- 首先来看现有的登陆功能代码。
登陆接口public interface LoginService { public String login(String username,String password,String type); }
- 实现类
public class LoginServiceImpl implements LoginService { @Override public String login(String username, String password, String type) { if(type == "account"){ System.out.println("账号登陆"); System.out.println("账号:"+username); System.out.println("密码:"+password); return "Success"; } return "Error!"; } }
- 此时我们需要增加上述功能,同时不更改原代码。
装饰器://WeChatDecorator 装饰器同样 实现LoginService接口 public class WeChatDecorator implements LoginService { //定义接口类型 private LoginService loginService; //通过构造的方式获取LoginService public WeChatDecorator(LoginService loginService){ this.loginService = loginService; } //新增微信登陆功能 public String WeChatLogin(String username, String password, String type){ if(type == "weChat"){ System.out.println("weChat登陆"); System.out.println("weChat:"+username); System.out.println("密码:"+password); return "Success"; } return "Error!"; } //原功能 @Override public String login(String username, String password, String type) { //功能增强 System.out.println("------记录日志-------"); return this.loginService.login(username,password,type); } }
- 测试结果如下