概述
设计模式(Design pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结,使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性。
分类
创建型模式(对象的创建)
简单工厂模式、工厂方法模式、抽象工厂模式、建造者模式、原型模式、单例模式
结构型模式(对象的组成)
外观模式、适配器模式、代理模式、装饰模式、桥接模式、组合模式、享元模式
行为型模式(对象的行为)
模板方法模式、观察者模式、状态模式、职责链模式、命令模式、访问者模式、策略模式、备忘录模式、迭代器模式、解释器模式
实例
简单工厂模式
概述
简单工厂模式又叫静态工厂方法模式,它定义一个具体的工厂类负责创建一些类的实例
代码演示
抽象类:
public abstract class Animal{
public abstract void eat();
}
实体类:
public class Dog extends Animal{
@Override
public void eat(){
System.out.printLn("具体类重写该方法");
}
}
测试类:
public class AnimalDemo{
public static void main(String[] args){
//具体类调用
Dog d = new Dog();
d.eat();
}
}
工厂类:
public class AnimalFactory{
private AnimalFactory(){
}
public static Dog createDog(){
return new Dog();
}
}
测试类:
public class AnimalDemo{
public static void main(String[] args){
//工程类使用
Dog dd =AnimalFactory.createDog();
dd.eat();
}
}
优点
客户端不需要在负责对象的创建,从而明确了各个类的职责。
缺点
这个静态工厂类负责所有对象的创建,如果有新的对象增加,或者某些对象的创建方式不同,就需要不断的修改工厂类,不利于后期的维护。
工厂方法模式
概述
工厂方法模式中抽象工厂类负责定义创建对象的接口,具体对象的创建工作由继承抽象工厂的具体类实现。
代码演示
抽象类:
public abstract class Animal{
public abstract void eat();
}
实体类:
public class Dog extends Animal{
@Override
public void eat(){
System.out.printLn("具体类重写该方法");
}
}
接口:
public interface Factory{
public abstract Animal createAnimal();
}
工厂类:
public class DogFactory implements Factory{
@Override
public Animal createAnimal(){
return new Dog();
}
}
测试类:
public class AnimalDemo{
public static void main(String[] args){
//工程类使用
Factory f = new DogFactory();
Animal a = f.createAnimal();
a.eat();
}
}
优点
客户端不需要再负责对象的创建,从而明确了各个类的职责,如果有新的对象增加,只需要增加一个具体的类和具体的工厂类即可,不影响已有的代码,后期维护容易,增强了系统的扩展性
缺点
需要额外的编写代码,增加了工作量
单例设计模式
概述
单例模式就是要确保类在内存中只有一个对象,该实例必须自动创建,并且对外提供。
优点
在系统内存中只存在一个对象,因此可以节约系统资源,对于一些需要频繁创建和销毁的对象单例模式无疑可以提高系统的性能
缺点
没有抽象层,因此扩展很难。
职责过重,在一定程度上违背了单一职责
饿汉式(类一加载就创建对象)
实体类:
public class Student{
//构造方法私有
private Student(){
}
//创建一个对象
private static Student s = new Student();
//提供公共的方法访问
//为了保证外界能够直接使用该方法,要加静态修饰
public static Studnet getStudnt(){
return s;
}
}
测试类:
/*
* 单例模式:保证类在内存中只有一个对象
*
* 如何保证类在内存中只有一个对象?
* 1、把构造方法私有
* 2、在成员位置自己创建一个对象
* 3、通过一个公共的方法提供访问
*/
public class StudentDemo{
public static void main(String[] args){
Student s1 = Student.getStudent();
Student s2 = Student.getStudent();
s1 == s2;
//如果s1==s2为true的话,则说明内存中只有一个对象且s1和s2为同一个对象,否则s1和s2为两个对象
}
}
懒汉式(使用该类时,才创建对象)
实体类:
public class Teacher{
//构造方法私有
private Teacher(){
}
//创建一个对象
private static Teacher t = null;
//提供公共的方法访问
//为了保证外界能够直接使用该方法,要加静态修饰
public static Teacher getTeacher(){
if(t == null){
t = new Teacher();
}
return t;
}
}
测试类:
/*
* 单例模式:保证类在内存中只有一个对象
*
* 如何保证类在内存中只有一个对象?
* 1、把构造方法私有
* 2、在成员位置自己创建一个对象
* 3、通过一个公共的方法提供访问
*/
public class TeacherDemo{
public static void main(String[] args){
Teacher t1 = Teacher.getTeacher();
Teacher t2 = Teacher.getTeacher();
s1 == s2;
//如果s1==s2为true的话,则说明内存中只有一个对象且s1和s2为同一个对象,否则s1和s2为两个对象
}
}