享元模式(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();
}
}
结果: