设计模式:是在大量实践中总结和理论化之后优选的代码结构、编程风格、以及解决问题的思考方式
共23种设计模式
单例设计模式:
1.解决的问题:使得一个类只能够创建一个对象
2.实现:
1)饿汉式:
class Singleton{
//1.私有化构造器,使得在类的外部不能调用此构造器
private Singleton(){
}
//2.在类的内部创建一个实例
private static Singleton instance = new Singleton();
//3.私有化此对象,通过共有的方法调用
//4.此公有方法,只能通过类 来调用,因此必须声明为static的,故同时类的实例也必须声明为static的
public static Singleton getInstance() {
return instance;
}
}
2)懒汉式:(可能存在线程安全问题)
class Singleton{
//1.
private Singleton(){
}
//2.
private static Singleton instance = null;
//3.
public static Singleton getInstance() {
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
懒汉式(解决了线程安全问题
package test;
public class TestSingleton {
}
class Singleton{
private Singleton() {
}
private static Singleton instance = null;
public static Singleton getInstance() {
if(instance == null) { //告知后面的线程,已经有线程创建了对象,直接不用等待,继续执行return(减少了等待时间,提高了后面线程的效率)
synchronized(Singleton.class){//当有线程进来之后,后面的线程就进不来了,在外面等待
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
)
模板方法设计模式:
1.解决的问题:功能内部一部分是确定的,一部分是不确定的。这时,可以把不确定的部分暴露出去,让子类去实现。
编写一个父类,父类提供了多个子类的通用方法,并把一个或多个方法留给其子类去实现,就是一种模板模式。