什么是享元模式
享元,顾名思义就是共享一些事先创建好的对象。
如果程序员需要频繁创建相同的对象,并且创建对象的代价很高,这个时候享元模式就是一个很不错的解决方案。
享元模式的成员
- 享元抽象类或者接口
- 享元工厂
- 享元类
- 客户端
代码实现
汽车接口(享元接口)
package com.stone.designpattern.flyweight;
/**
* @author Stone Wang
* Interface of vehicle
* has two methods start and stop with void return
*
*/
public interface IVehicle {
public static final String VERSION = "1.0";
public void start();
public void stop();
}
汽车实现(享元类)
package com.stone.designpattern.flyweight;
public class Vehicle implements IVehicle {
private final String type;
public Vehicle(String type) {
this.type = type;
}
public String getType() {
return type;
}
@Override
public void start() {
System.out.println(String.format("Vehicle %s is started", type));
}
@Override
public void stop() {
System.out.println(String.format("Vehicle %s is stopped", type));
}
}
汽车工厂(享元工厂)
package com.stone.designpattern.flyweight;
import java.util.*;
public class VehicleFactory {
private static final Map<String, IVehicle> vehicleMap = new HashMap<>();
public static IVehicle getVehicle(String type) {
if(vehicleMap.containsKey(type)) {
return vehicleMap.get(type);
}
IVehicle vehicle = new Vehicle(type);
vehicleMap.put(type, vehicle);
return vehicle;
}
}
客户端代码(客户端)
package com.stone.designpattern.flyweight;
public class Main {
public static void main(String[] args) {
String[] types = new String[] {"Car", "Bus", "Truck", "Van", "Metro"};
for(int i=0; i<10; i++) {
IVehicle v = VehicleFactory.getVehicle(types[(int)(Math.random() * types.length)]);
v.start();
v.stop();
}
}
}