委派模式和门面模式

委派模式

介绍

委派模式不是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("刘德华");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值