定义:
为其他对象提供一种代理以控制对这个对象的访问
使用使用场景:
1.当无法或不想直接访问某个对象或者访问某个对象存在困难时可以通过一个代理对象来间接访问,为了保证客户端使用的透明性,委托对象与代理对象需要实现相同的接口
实战
不同API发送通知为例来说明代理模式
64dpHeight、256dp Height和headsUpContentView
定义一个抽象类
public abstract class Notify {
protected Context context;
protected NotificationManager nm;
protected NotificationCompat.Builder builder;
public Notify(Context context) {
this.context = context;
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, Notification.class),
PendingIntent.FLAG_UPDATE_CURRENT));
}
public abstract void send();
public abstract void cancel();
}
普通的通知实现类
public class NotifyNormal extends Notify {
public NotifyNormal(Context context) {
super(context);
}
@Override
public void send() {
Notification n = builder.build();
n.contentView = new RemoteViews(context.getPackageName(), R.layout.activity_main);
nm.notify(0, n);
}
@Override
public void cancel() {
nm.cancel(0);
}
}
public class NotifyBig extends Notify {
public NotifyBig(Context context) {
super(context);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void send() {
Notification n = builder.build();
n.contentView = new RemoteViews(context.getPackageName(), R.layout.activity_main);
n.bigContentView = new RemoteViews(context.getPackageName(), R.layout.activity_main);
nm.notify(0, n);
}
@Override
public void cancel() {
nm.cancel(0);
}
}
NotifyHeadUp
public class NotifyHeadsUp extends Notify {
public NotifyHeadsUp(Context context) {
super(context);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void send() {
Notification n = builder.build();
n.contentView = new RemoteViews(context.getPackageName(), R.layout.activity_main);
n.bigContentView = new RemoteViews(context.getPackageName(), R.layout.activity_main);
n.headsUpContentView = new RemoteViews(context.getPackageName(), R.layout.activity_main);
nm.notify(0, n);
}
@Override
public void cancel() {
nm.cancel(0);
}
}
添加一个代理类NotifyProxy
public class NotifyProxy extends Notify {
private Notify notify;
public NotifyProxy(Context context) {
super(context);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notify = new NotifyHeadsUp(context);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
notify = new NotifyBig(context);
} else {
notify = new NotifyNormal(context);
}
}
@Override
public void send() {
notify.send();
}
@Override
public void cancel() {
notify.cancel();
}
}
用户调用
public class ProxyActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) { super.onCreate(savedInstanceState, persistentState); findViewById(R.id.activity_main).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new NotifyProxy(ProxyActivity.this).send(); } }); } }