美文网首页
设计模式 Builder 模式

设计模式 Builder 模式

作者: Android一行代码 | 来源:发表于2022-06-30 15:50 被阅读0次

    核心就是隐藏构造方法,通过一个静态内部类封装构造。隐藏构建过程。

    主要使用于对象比较复杂的时候, Android中我们使用最多的就是AlertDialog了。

    
    public class MediaPlayer {
        private LivingPlayer livingPlayer;
        private VidoPlayter vidoPlayter;
        private String PlayUrl;
        private Callback mcallback;
    
        public MediaPlayer(Builder builder) {
            this.livingPlayer=builder.livingPlayer;
            this.vidoPlayter=builder.vidoPlayter;
            this.PlayUrl=builder.PlayUrl;
            this.mcallback=builder.mcallback;
        }
        interface Callback {
            void callback();
        }
        public static class Builder{
            private LivingPlayer livingPlayer;
            private VidoPlayter vidoPlayter;
            private String PlayUrl;
            private Callback mcallback;
    
            public Builder setLivingPlayer(LivingPlayer livingPlayer) {
                this.livingPlayer = livingPlayer;
                return this;
            }
    
            public Builder setVidoPlayter(VidoPlayter vidoPlayter) {
                this.vidoPlayter = vidoPlayter;
                return this;
            }
            public Builder setPlayUrl(String playUrl) {
                PlayUrl = playUrl;
                return this;
            }
            public Builder setCallback(  Callback callback) {
                mcallback = callback;
                return this;
            }
    
            public MediaPlayer build(){
                return  new MediaPlayer(this);
            }
        }
    }
    

    使用

            MediaPlayer.Builder builder=new MediaPlayer.Builder();
            builder.setLivingPlayer(new LivingPlayer(AppApplication.appContext));
            MediaPlayer livingplayer=builder.build();

    相关文章

      网友评论

          本文标题:设计模式 Builder 模式

          本文链接:https://www.haomeiwen.com/subject/ynwfbrtx.html