设计模式 Builder 模式
2022-06-30 本文已影响0人
Android一行代码
核心就是隐藏构造方法,通过一个静态内部类封装构造。隐藏构建过程。
主要使用于对象比较复杂的时候, 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();