本文主要是介绍flyweight享元模式-Java实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
什么是享元模式
享元,顾名思义就是共享一些事先创建好的对象。
如果程序员需要频繁创建相同的对象,并且创建对象的代价很高,这个时候享元模式就是一个很不错的解决方案。
享元模式的成员
- 享元抽象类或者接口
- 享元工厂
- 享元类
- 客户端
代码实现
汽车接口(享元接口)
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;}@Overridepublic void start() {System.out.println(String.format("Vehicle %s is started", type));}@Overridepublic 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();}}}
这篇关于flyweight享元模式-Java实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!