文章目录
- 单例模式
- 工厂模式
- 建造者模式
- 原型模式
单例模式
单例模式有饿汉式 和 懒汉式。这个我觉得无需多言,每个学过Java的都知道。
1.单例的使用:我一般就是用饿汉式,因为App开发的开发一般数据处理并不复杂,所以直接使用饿汉式即可。
2.单例的特殊使用场景,线程单例。这个使用ThreadLocal。(后续补充)
3.单例使用注意事项:由于单例是静态修饰的,所以他无法回收。所以使用单例切记不能传Context,也不能占用太多内存。
工厂模式
这个也没啥好说的,就是根据条件生成不同的对象。
class ProductFactory {public static Product createProduct(String type) {switch (type) {case "A":return new ConcreteProductA();case "B":return new ConcreteProductB();default:throw new IllegalArgumentException("Unknown product type");}}
}
建造者模式
建造者模式本质就是处理构造函数比较多的问题。
相对于Kotlin的默认参数。显的很啰嗦。可读性也不好。
原型模式
通过复制现有对象来创建新的对象,而无需显式地调用构造函数。这种方式既可以提高对象的创建效率,又可以避免因为频繁创建对象而导致内存占用过高的问题
原型模式与其他设计模式有点不一样的地方。Java系统已提供接口,需要基于系统接口去处理。
// 原型接口
interface Prototype extends Cloneable {Prototype clone() throws CloneNotSupportedException;
}// 具体原型类
class Resume implements Prototype {private String name;private int age;private List<String> skills; // 引用类型字段public Resume(String name, int age, List<String> skills) {this.name = name;this.age = age;this.skills = skills;}// 浅克隆实现@Overridepublic Resume clone() throws CloneNotSupportedException {return (Resume) super.clone();}// 深克隆实现public Resume deepClone() throws CloneNotSupportedException {Resume cloned = (Resume) super.clone();cloned.skills = new ArrayList<>(this.skills); // 创建新集合return cloned;}// 修改技能列表public void addSkill(String skill) {this.skills.add(skill);}@Overridepublic String toString() {return String.format("Resume{name='%s', age=%d, skills=%s}", name, age, skills);}
}
实际开发中很少见到,一般的Android应用开发,对内存的要求还没有这么严格。
目前只在okhttp框架中见过。