设计模式java——享元模式

享元模式(Flyweight):运用共享技术有效地支持大量细粒度的对象。

享元模式Demo:

/**
 * 2018年4月9日下午9:35:43
 */
package com.Designpattern;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xinwenfeng
 *
 */
public class TestFlyweight {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		FlyweightFactory flyweightFactory = new FlyweightFactory();
		Flyweight_testdrive flyweight1 = flyweightFactory.getFlyweight("大众");
		flyweight1.testDrive("高尔夫");
		System.out.println("size:"+flyweightFactory.getSizeOfTestDrive());
		Flyweight_testdrive flyweight2 = flyweightFactory.getFlyweight("大众");
		flyweight2.testDrive("Arteon");
		System.out.println("size:"+flyweightFactory.getSizeOfTestDrive());
		Flyweight_testdrive flyweight3 = flyweightFactory.getFlyweight("丰田");
		flyweight3.testDrive("卡罗拉");
		System.out.println("size:"+flyweightFactory.getSizeOfTestDrive());
		Flyweight_testdrive flyweight4 = flyweightFactory.getFlyweight("丰田");
		flyweight4.testDrive("Avalon");
		System.out.println("size:"+flyweightFactory.getSizeOfTestDrive());
		Flyweight_testdrive flyweight5 = flyweightFactory.getFlyweight("马自达");
		flyweight5.testDrive("马自达6");
		System.out.println("size:"+flyweightFactory.getSizeOfTestDrive());
		Flyweight_testdrive flyweight6 = flyweightFactory.getFlyweight("马自达");
		flyweight6.testDrive("MX-5");
		System.out.println("size:"+flyweightFactory.getSizeOfTestDrive());
		Flyweight_testdrive flyweight7 = flyweightFactory.getFlyweight("马自达");
		flyweight7.testDrive("CX-8");
		System.out.println("size:"+flyweightFactory.getSizeOfTestDrive());
	}

}
abstract class Flyweight_testdrive{
	protected String carCompany;
	protected Flyweight_testdrive(String carCompany) {
		this.carCompany = carCompany;
	}
	public abstract void testDrive(String carName);
}
class TestDrive extends Flyweight_testdrive{

	protected TestDrive(String carCompany) {
		super(carCompany);
	}

	@Override
	public void testDrive(String carName) {
		System.out.println("试驾【"+carCompany+"】公司的["+carName+"]汽车");
	}
	
}
class FlyweightFactory{
	private Map<String,Flyweight_testdrive> testDrives = new HashMap<>();
	
	public Flyweight_testdrive getFlyweight(String company) {
		if(!testDrives.containsKey(company)) {
			testDrives.put(company, new TestDrive(company));
		}
		return testDrives.get(company);
	}
	public int getSizeOfTestDrive() {
		return testDrives.size();
	}
}

结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值