1、了解什么是设计模式 ?
设计模式(Design Pattern),是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性、程序的重用性。是软件开发人员在软件开发过程中面临的一般问题的解决方案。这些解决方案是众多软件开发人员经过相当长的一段时间的试验和错误总结出来的。
2、查阅相关资料,掌握其中几项设计模式。
一、先谈一谈 单例设计模式(最近的项目里用到)
简单来说就是一个类只能创建一个实例,比如说 任务管理器 ,你不可能同时打开多个管理器去管理任务(没用而且浪费资源)
单例模式分两种:
懒汉式
public class Singleton {
/* 1. 懒汉式
特点:
1. 非线程安全
2. 是否lazy初始化(懒加载、延时加载):是
*/
private static Singleton instance;
private Singleton(){
}
//加synchronized则线程安全
public static Singleton getInstance(){
if (instance == null) {
instance = new Singleton();
}
return instance;
}
public static void main(String[] args) {
Singleton instance1 = Singleton.getInstance();
Singleton instance2 = Singleton.getInstance();
System.out.println(instance1);
System.out.println(instance2);
if(instance1 == instance2 && instance2 == instance3){
System.out.println("同一个实例");
}
}
}
饿汉式
public class Singleton {
/* 1. 饿汉式
特点:
1. 线程安全
2. 非lazy初始化(非延时加载):否
*/
private static Singleton instance = new Singleton();
private Singleton(){
}
public static Singleton getInstance() {
return instance;
}
public static void main(String[] args) {
Singleton instance1 = Singleton.getInstance();
Singleton instance2 = Singleton.getInstance();
System.out.println(instance1);
System.out.println(instance2);
if(instance1 == instance2 && instance2 == instance3){
System.out.println("同一个实例");
}
}
}
二、状态模式
在状态模式(State Pattern)中,类的行为是基于它的状态改变的。这种类型的设计模式属于行为型模式。在状态模式中,我们创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象。
例如创建一个 State 接口和实现了 State 接口的实体状态类。Context 是一个带有某个状态的类。StatePatternDemo,我们的演示类使用 Context 和状态对象来演示 Context 在状态改变时的行为变化。: