1.单例模式
1.1 步骤
1.静态声明实例变量
2.私有化构造函数
3.提供静态外部访问方法
1.2 示例
//只有内部类可以为static。
public class SingIn{
//在自己内部定义自己的一个实例,只供内部调用
private static final SingIn instance = new SingIn();
private SingIn(){
}
//这里提供了一个供外部访问本class的静态方法,可以直接访问
public static SingIn getInstance(){
return instance;
}
}
1.3 线程安全单例
public class SingIn{
/***
* 一种常用的形式
*/
private static SingIn instance = null;
public static SingIn getInstance() {
// 这个方法比上面有所改进,不用每次都进行生成对象,只是第一次
// 使用时生成实例,提高了效率!
if (instance == null) {
synchronized(SingIn.class){
if(instance == null) {
instance = new SingIn();
}
}
}
return instance;
}
}
2 观察者模式
2.1 定义一个被观察类
public class User {
//观察者集合
private ArrayList<UserObserser> mObserverList = new ArrayList<>();
private String name = "";
private int age = 0;
public User(){
}
public User(String name, int age){
this.age = age;
this.name = name;
}
//注册观察者
public void registerObserver(UserObserser obserser) {
if(obserser != null && !mObserverList.contains(obserser)){
mObserverList.add(obserser);
}
}
//注销观察者
public void unregisterObserver(UserObserser obserser){
if (mObserverList.contains(obserser)){
mObserverList.remove(obserser);
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
notifyNameChanged(name);
}
//通知所有观察者姓名改变
private void notifyNameChanged(String name) {
for (int i=0;i<mObserverList.size();i++){
mObserverList.get(i).nameChanged(name);
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
notifyAgeChanged(age);
}
//通知所有观察者年龄改变
private void notifyAgeChanged(int age) {
for (int i=0;i<mObserverList.size();i++){
mObserverList.get(i).ageChanged(age);
}
}
}
观察者接口
public abstract class UserObserser {
abstract void nameChanged(String name);
abstract void ageChanged(int age);
}
使用
public class MainActivity extends AppCompatActivity {
private int index = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final User user1 = new User("Tom1",123);
final User user2 = new User("Tom2",124);
final Button button1 = findViewById(R.id.btn_1);
final Button button2 = findViewById(R.id.btn_2);
button1.setText(user1.getName() + "===" + user1.getAge());
button2.setText(user2.getName() + "===" + user2.getAge());
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
user1.setName("李浩"+(index++)+"被点击");
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
user2.setAge(index++);
}
});
user1.registerObserver(new UserObserser() {
@Override
void nameChanged(String name) {
button1.setText(user1.getName() + "===" + user1.getAge());
}
@Override
void ageChanged(int age) {
button1.setText(user1.getName() + "===" + user1.getAge());
}
});
user2.registerObserver(new UserObserser() {
@Override
void nameChanged(String name) {
button2.setText(user2.getName() + "===" + user2.getAge());
}
@Override
void ageChanged(int age) {
button2.setText(user2.getName() + "===" + user2.getAge());
}
});
}
}
观察者uml类图

3 适配器模式
3.1 作用
适配器模式(Adapter):将一个类的接口转换成客户希望的另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
3.2 适用场景
业务的接口与工作的类不兼容,(比如:类中缺少实现接口的某些方法)但又需要两者一起工作
在现有接口和类的基础上为新的业务需求提供接口
3.3 示例
Usb接口类
public interface Usb {
void store();
void takeAlong();
}
手机类
public class AbsPhone implements Usb {
public void call() {
System.out.println("AbsPhone call");
}
public void sms() {
System.out.println("AbsPhone sms");
}
@Override
public void store() {
System.out.println("AbsPhone implements usb's store methond");
}
public void takeAlong() {
System.out.println("AbsPhone implements usb's takeAlong methond");
}
}
小米手机类
public class XiaoMi extends AbsPhone {
@Override
public void call() {
System.out.println("XiaoMi call");
}
@Override
public void sms() {
System.out.println("XiaoMi call");
}
@Override
public void store() {
System.out.println("XiaoMi need usb's store method");
}
}
华为手机类
public class HuaWei extends AbsPhone {
@Override
public void call() {
System.out.println("HuaWei call");
}
@Override
public void sms() {
System.out.println("HuaWei sms");
}
@Override
public void takeAlong() {
System.out.println("HuaWei need usb's takeAlong method");
}
}
使用
//适配器模式
HuaWei huaWei = new HuaWei();
XiaoMi xiaoMi = new XiaoMi();
huaWei.call();
huaWei.sms();
huaWei.takeAlong();
huaWei.store();
xiaoMi.call();
xiaoMi.sms();
xiaoMi.store();
xiaoMi.takeAlong();
适配器模式uml类图

4.装饰器模式
4.1 功能
装饰者模式实现的是从一个对象外部给对象添加功能,相当于改变了对象的外观,装饰过的对象,从外部系统来看已经不再是原来的对象,而是经过一系列装饰器装饰过的对象。
装饰者模式最大的好处就是灵活,它能够灵活的改变一个的对象的功能,并且是动态组合形式。另外好处就是代码复用,因为每个装饰器是独立的,可以给一个对象多次增加同一个装饰器,也可以同一个装饰器装饰不同对象。
在面向对象设计中:有一条基本规则
尽量使用对象组合,而不是对象继承来扩展和复用功能
4.2 示例
public abstract class Component {
//抽象方法
public abstract void operation();
}
public class ConcreteComponent extends Component {
@Override
public void operation() {
System.out.print("ConcreteComponent.operation");
}
}
public abstract class Decorator extends Component {
public Component mComponent;
public Decorator(Component component){
this.mComponent = component;
}
@Override
public void operation() {
mComponent.operation();
}
}
public class ConcreteDecorationA extends Decorator {
public ConcreteDecorationA(Component component) {
super(component);
}
public int operationA(){
System.out.print("ConcreteDecorationA.operationA");
return 0;
}
@Override
public void operation() {
operationA();
super.operation();
}
}
//装饰者模式
Component component = new ConcreteComponent();
Decorator decorator = new ConcreteDecorationA(component);
decorator.operation();
4.2 uml类图描述

装饰器模式、代理模式、装饰者模式区别?
5 创建者(工厂)模式
5.1 简单工厂模式uml类图

5.2 工厂模式uml图

5.3 抽象工厂uml

6 策略模式
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使他们可以相互替换,让算法独立于使用它的客户而独立变化。
6.1 策略模式uml类图

6.2 示例
public interface Strategy {
void travel();
}
public class WalkStrategy implements Strategy{
@Override
public void travel() {
System.out.println("walk");
}
}
public class PlaneStrategy implements Strategy{
@Override
public void travel() {
System.out.println("plane");
}
}
public class SubwayStrategy implements Strategy{
@Override
public void travel() {
System.out.println("subway");
}
}
public class TravelContext {
Strategy strategy;
public Strategy getStrategy() {
return strategy;
}
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public void travel() {
if (strategy != null) {
strategy.travel();
}
}
}
public class Main {
public static void main(String[] args) {
TravelContext travelContext=new TravelContext();
travelContext.setStrategy(new PlaneStrategy());
travelContext.travel();
travelContext.setStrategy(new WalkStrategy());
travelContext.travel();
travelContext.setStrategy(new SubwayStrategy());
travelContext.travel();
}
}
输出
plane
walk
subway
7 职责链模式
职责链模式:使多个对象都有机会处理同一个请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
为完成同一个请求,如果存在多个请求处理器以及未知请求处理器个数或者请求处理器可动态配置的情况下,可以考虑使用责任链模式。如OKHttp的拦截器就是使用的责任链模式。例如okhttp网络请求框架
7.1示例
请求类 (这里的Request和Result其实还用到了Builder模式)
public class Request {
private String name;
private String reason;
private int days;
private String groupLeaderInfo;
private String managerInfo;
private String departmentHeaderInfo;
private String customInfo;
public Request(Builder builder) {
super();
this.name = builder.name;
this.reason = builder.reason;
this.days = builder.days;
this.groupLeaderInfo = builder.groupLeaderInfo;
this.managerInfo = builder.managerInfo;
this.departmentHeaderInfo = builder.departmentHeaderInfo;
this.customInfo = builder.customInfo;
}
public static class Builder {
public String name;
public String reason;
public int days;
public String groupLeaderInfo;
public String managerInfo;
public String departmentHeaderInfo;
public String customInfo;
public Builder() {
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setReason(String reason) {
this.reason = reason;
return this;
}
public Builder setDays(int days) {
this.days = days;
return this;
}
public Builder setGroupLeaderInfo(String groupLeaderInfo) {
this.groupLeaderInfo = groupLeaderInfo;
return this;
}
public Builder setManagerInfo(String managerInfo) {
this.managerInfo = managerInfo;
return this;
}
public Builder setDepartmentHeaderInfo(String departmentHeaderInfo) {
this.departmentHeaderInfo = departmentHeaderInfo;
return this;
}
public Builder setCustomInfo(String customInfo) {
this.customInfo = customInfo;
return this;
}
public Builder newRequest(Request request) {
this.name = request.name;
this.days = request.days;
this.reason = request.reason;
if (request.groupLeaderInfo != null
&& !request.groupLeaderInfo.equals("")) {
this.groupLeaderInfo = request.groupLeaderInfo;
}
if (request.managerInfo != null && !request.managerInfo.equals("")) {
this.managerInfo = request.managerInfo;
}
if (request.departmentHeaderInfo != null
&& !request.departmentHeaderInfo.equals("")) {
this.departmentHeaderInfo = request.departmentHeaderInfo;
}
if (request.customInfo != null && !request.customInfo.equals("")) {
this.customInfo = request.customInfo;
}
return this;
}
public Request build() {
return new Request(this);
}
}
public String name() {
return name;
}
public String reason() {
return reason;
}
public int days() {
return days;
}
public String groupLeaderInfo() {
return groupLeaderInfo;
}
public String managerInfo() {
return managerInfo;
}
public String departmentHeaderInfo() {
return departmentHeaderInfo;
}
public String customInfo() {
return customInfo;
}
@Override
public String toString() {
return "Request [name=" + name + ", reason=" + reason + ", days="
+ days + ",customInfo=" + customInfo + ", groupLeaderInfo="
+ groupLeaderInfo + ", managerInfo=" + managerInfo
+ ", departmentHeaderInfo=" + departmentHeaderInfo + "]";
}
}
响应类
public class Result {
private boolean customRatify;
private boolean groupRatify;
private boolean managerRatify;
private boolean departRatify;
private String info;
public Result(Builder builder) {
super();
this.info = builder.info;
this.customRatify = builder.customRatify;
this.groupRatify = builder.groupRatify;
this.managerRatify = builder.managerRatify;
this.departRatify = builder.departRatify;
}
public static class Builder {
private boolean customRatify;
private boolean groupRatify;
private boolean managerRatify;
private boolean departRatify;
private String info;
public Builder(){
}
public Builder setCustomRatify(boolean customRatify) {
this.customRatify = customRatify;
return this;
}
public Builder setGroupRatify(boolean groupRatify) {
this.groupRatify = groupRatify;
return this;
}
public Builder setManagerRatify(boolean managerRatify) {
this.managerRatify = managerRatify;
return this;
}
public Builder setDepartRatify(boolean departRatify) {
this.departRatify = departRatify;
return this;
}
public Builder setInfo(String info){
this.info = info;
return this;
}
public Builder newResult(Result res){
this.info = res.info;
this.customRatify = res.customRatify;
this.groupRatify = res.groupRatify;
this.managerRatify = res.managerRatify;
this.departRatify = res.departRatify;
return this;
}
public Result build(){
return new Result(this);
}
}
public boolean customRatify() {
return customRatify;
}
public boolean groupRatify() {
return groupRatify;
}
public boolean managerRatify() {
return managerRatify;
}
public boolean departRatify() {
return departRatify;
}
public String info() {
return info;
}
@Override
public String toString() {
return "Result [customRatify=" + customRatify + ", groupRatify="
+ groupRatify + ", managerRatify=" + managerRatify
+ ", departRatify=" + departRatify + ", info=" + info + "]";
}
}
拦截器职责链接口
public interface Interceptor {
public Result intercept(Chain chain);
public interface Chain {
Request request();
Result proceed(Request request);
}
}
职责链实现类
public class RealChain implements Chain{
public Request request;
public ArrayList<Interceptor> interceptors;
public int index;
public RealChain(Request request,ArrayList<Interceptor> interceptors,int index){
this.request = request;
this.interceptors = interceptors;
this.index = index;
}
@Override
public Request request() {
return request;
}
@Override
public Result proceed(Request request) {
Result res = null;
if(interceptors.size() >= index){
RealChain realchain = new RealChain(request,interceptors,index+1);
Interceptor interceptor = interceptors.get(index);
res = interceptor.intercept(realchain);
}
return res;
}
}
拦截器
public class CustomInterceptor implements Interceptor {
@Override
public Result intercept(Chain chain) {
Request request = chain.request();
Result res = null;
//加工请求
Request newRquest = new Request.Builder()
.newRequest(request)
.setCustomInfo("Custom:我问问GroupLeader")
.build();
System.out.println("1:customReqest===>"+newRquest.customInfo());
//处理请求
res = chain.proceed(newRquest);
Result.Builder newresBuilder = new Result.Builder()
.newResult(res);
//GroupLeader同意就可以
newresBuilder.setCustomRatify(res.groupRatify());
System.out.println("-1:customResult");
//加工结果
return newresBuilder.build();
}
}
public class GroupLeaderInterceptor implements Interceptor {
@Override
public Result intercept(Chain chain) {
Request request = chain.request();
Result res = null;
//加工请求
Request newRquest = new Request.Builder()
.newRequest(request)
.setGroupLeaderInfo("GroupLeader:我问问Manager")
.build();
System.out.println("2:GroupLeaderReqest===>"+newRquest.groupLeaderInfo());
//处理请求
res = chain.proceed(newRquest);
Result.Builder newresBuilder = new Result.Builder()
.newResult(res);
//Manager同意就可以
newresBuilder.setGroupRatify(res.managerRatify());
System.out.println("-2:GroupLeaderReqest");
//加工结果
return newresBuilder.build();
}
}
public class ManagerInterceptor implements Interceptor {
@Override
public Result intercept(Chain chain) {
Request request = chain.request();
Result res = null;
//加工请求
Request newRquest = new Request.Builder()
.newRequest(request)
.setManagerInfo("Manager:我问问DepartmentHeader")
.build();
System.out.println("3:ManagerReqest===>"+newRquest.managerInfo());
//处理请求
res = chain.proceed(newRquest);
Result.Builder newresBuilder = new Result.Builder()
.newResult(res);
//DepartmentHeader同意就可以
newresBuilder.setManagerRatify(res.departRatify());
System.out.println("-3:ManagerReqest");
//加工结果
return newresBuilder.build();
}
}
public class DepartmentHeaderInterceptor implements Interceptor {
@Override
public Result intercept(Chain chain) {
Request request = chain.request();
Result.Builder resbuilder = new Result.Builder();
System.out.println("4:DepartmentHeader");
//对request 加工
if(request.name().equals("mike")){
resbuilder.setInfo("好好干");
resbuilder.setDepartRatify(true);
}else{
resbuilder.setInfo("不干拉倒");
resbuilder.setDepartRatify(false);
}
return resbuilder.build();
}
}
执行
public static void main(String[] args) {
ArrayList<Interceptor> interceptors = new ArrayList<Interceptor>();
interceptors.add(new CustomInterceptor());
interceptors.add(new GroupLeaderInterceptor());
interceptors.add(new ManagerInterceptor());
interceptors.add(new DepartmentHeaderInterceptor());
Request req = new Request.Builder()
.setName("mike")
.setReason("看电影")
.setDays(3)
.build();
RealChain chain = new RealChain(req,interceptors,0);
Result proceed = chain.proceed(req);
System.out.println(proceed.toString());
}
输出
1:customReqest===>Custom:我问问GroupLeader
2:GroupLeaderReqest===>GroupLeader:我问问Manager
3:ManagerReqest===>Manager:我问问DepartmentHeader
4:DepartmentHeader
-3:ManagerReqest
-2:GroupLeaderReqest
-1:customResult
Result [customRatify=true, groupRatify=true, managerRatify=true, departRatify=true, info=好好干]
由此可见,职责链的执行方式类似于递归,通过一系列的链式加工处理某个请求,使得发送者和接受者充分解耦。

7.2 职责链设计模式uml类图

网友评论