委派模式与门面模式 委派模式介绍Demo类图总结 门面模式介绍Demo
委派模式 介绍
委派模式不是23中设计模式之一,是一种行为型模式。委派者好比一个领导者。自己不用干活,将任务分配给其他人,比如老师任命劳动组长,劳动组长分配任务,劳动组长不用干活,这个模式有点像代理模式
Demo // 学生接口,public interface Student { void doCleaning(String task);}// 学生一,接受任务public class StudentOne implements Student { @Override public void doCleaning(String task) { System.out.println("学生一打扫:"+task); }}// 学生二,接受任务public class StudentTwo implements Student { @Override public void doCleaning(String task) { System.out.println("学生二打扫:"+task); }}// 劳动组长,接受任务,分派任务public class LabourGroupLeader implements Student{ @Override public void doCleaning(String task) { if("排座位".equals(task)){ new StudentOne().doCleaning(task); }else if("扫地".equals(task)){ new StudentTwo().doCleaning(task); } }}// 老师,发送任务public class Teacher { public static void main(String[] args) { LabourGroupLeader sd = new LabourGroupLeader(); sd.doCleaning("排座位"); }} 类图 总结委派模式在Java源码和spring中都用到挺多的,这个模式我们有时候会不知觉的用到,但我们可能写的时候并不知道这个是委派模式,所以说并不需要刻意为写个设计模式来重写代码。
门面模式 介绍门面模式也叫外观模式,是一种结构型模式,门面模式很简单,首先我们先假设要实现播放音乐,先要下载歌曲,然后下载歌词,然后下载歌手写真,这一系列操作需要去调用,如下面所示,
Demo public class Player { public static void main(String[] args) { Music music = new Music(); Lyric lyric = new Lyric(); SingerPhoto singerPhoto = new SingerPhoto(); music.download("张学友"); lyric.download("张学友"); singerPhoto.download("张学友"); System.out.println("开始播放!"); }}这样我们播放一首音乐都要写这么多重复的代码,让我们来简单重构一下,这样的话我们是不是只通过一个方法就可以实现播放音乐了,这就是门面模式,就是这么的简单,我们平常写代码时会有很多地方用到这个模式,只不过我们不清楚他在设计模式中也有体现罢了,所以说设计模式将我们平常写代码比较好的模式给总结了出来。让我们有了更清晰的认识
public class FacadeService { public static void playMusic(String name) { Music music = new Music(); Lyric lyric = new Lyric(); SingerPhoto singerPhoto = new SingerPhoto(); music.download(name); lyric.download(name); singerPhoto.download(name); System.out.println("开始播放!"); }}public class Player { public static void main(String[] args) { FacadeService facadeService = new FacadeService(); facadeService.playMusic("张学友"); facadeService.playMusic("刘德华"); }}