设计模式分类曲线图
接下来介绍图中常用的几种设计模式:
1单例模式
在一个应用程序中,某个类的实例对象只有一个,因为构造器是被private修饰的,所以无法直接去new对象,一般通过getInstance()的方法来获取它们的实例。getInstance()的返回值是一个对象的引用。对应的demo如下:
public class Singleton {
private static Singleton singleton;
private Singleton() {
}
public static Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
常见的单例模式有懒汉式写法和饿汉式写法
懒汉式写法(对应的代码如下)
public class Singleton {
private static Singleton instance;
private Singleton (){
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
饿汉式写法(对应的代码如下)
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){
}
public static Singleton getInstance() {
return instance;
}
}
2 观察者模式
指多个对象间存在一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。这种模式有时又称作发布-订阅模式、模型-视图模式,它是对象行为型模式。对应的demo如下:
//被观察者接口
public interface Observable {
//添加一个观察者
public void addObserver(Observer observer);
//删除一个观察者
public void deleteObserver(Observer observer);
//当被观察者有所行动的是,通知观察者
public void notifyObserver(String context);
}
public interface IStar {
//明星也要吃饭啊
public void eat();
//明星的行动
public void action();
}
public class ZhaoLiYing implements IStar,Observable{
private ArrayList<Observer> observerList=new ArrayList<>();
@Override
public void eat() {
System.out.println("颖宝吃饭ing......");
this.notifyObserver("颖宝开始吃饭了!!!");
}
@Override
public void action() {
System.out.println("颖宝电视剧宣传中......");
this.notifyObserver("赵丽颖宣传电视剧!!!");
}
@Override
public void addObserver(Observer observer) {
this.observerList.add(observer);
}
@Override
public void deleteObserver(Observer observer)