flyweight享元模式-Java实现

什么是享元模式

享元,顾名思义就是共享一些事先创建好的对象。
如果程序员需要频繁创建相同的对象,并且创建对象的代价很高,这个时候享元模式就是一个很不错的解决方案。

享元模式的成员

  1. 享元抽象类或者接口
  2. 享元工厂
  3. 享元类
  4. 客户端

代码实现

汽车接口(享元接口)

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();
		}

	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值