设计模式
单例模式
一 懒汉式 (在调用类的实例化方法时创建实例)
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return singleton;
}
}
二 饿汉式(在初始化类时创建实例)
public class Singleton {
private static Singleton singleton;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(singleton==null){
singleton = new Singleton();
}
return singleton;
}
}
单例模式优点
- 只存在一个对象实例,节省内存
- 避免频繁的创建销毁对象
- 可以全局访问
工厂方法模式
四要素:
- 工厂接口
- 工厂实现
- 产品接口
- 产品实现
好处: 解耦
适用场景:需要创建一个复杂对象的时候(造汽车)
造一辆汽车需要组装组件,若不适用工厂模式需要对一些组件实例化再配置到汽车中。
class Engine {
public void getStyle(){
System.out.println("这是汽车的发动机");
}
}
class Underpan {
public void getStyle(){
System.out.println("这是汽车的底盘");
}
}
class Wheel {
public void getStyle(){
System.out.println("这是汽车的轮胎");
}
}
public class Client {
public static void main(String[] args) {
Engine engine = new Engine();
Underpan underpan = new Underpan();
Wheel wheel = new Wheel();
ICar car = new Car(underpan, wheel, engine);
car.show();
}
}
使用工厂模式可以,将具体的创建对象过程隐藏在工厂实现类中,虽然多引入了两个类,但是调用者不必再关注具体的创建过程,只需创建相应的工厂类获取对象。
interface IFactory {
public ICar createCar();
}
class Factory implements IFactory {
public ICar createCar() {
Engine engine = new Engine();
Underpan underpan = new Underpan();
Wheel wheel = new Wheel();
ICar car = new Car(underpan, wheel, engine);
return car;
}
}
public class Client {
public static void main(String[] args) {
IFactory factory = new Factory();
ICar car = factory.createCar();
car.show();
}
}
抽象工厂模式
抽象工厂模式是工厂方法模式的升级,是为了解决当拥有相似产品时的问题
interface IProduct1 {
public void show();
}
interface IProduct2 {
public void show();
}
class Product1 implements IProduct1 {
public void show() {
System.out.println("这是1型产品");
}
}
class Product2 implements IProduct2 {
public void show() {
System.out.println("这是2型产品");
}
}
interface IFactory {
public IProduct1 createProduct1();
public IProduct2 createProduct2();
}
class Factory implements IFactory{
public IProduct1 createProduct1() {
return new Product1();
}
public IProduct2 createProduct2() {
return new Product2();
}
}
public class Client {
public static void main(String[] args){
IFactory factory = new Factory();
factory.createProduct1().show();
factory.createProduct2().show();
}
}