什么是享元模式
将对象中有共同特性的属性提取出来进行共享,避免对象的重复创建从而减少内存的消耗
示例图
图片.png示例场景
6个用户分别购买不同类别的水果,有苹果 梨 橙子,虽然购买了6次但是实例化的水果类别为3种。(内部状态:可以共享的属性为水果类别 外部状态:不可共享的属性为用户名称)
示例代码
1.创建Fruits抽象类
public abstract class Fruits {
public abstract void buyFruits(User user);
}
2.创建ConcreteFruits具体水果实现类
public class ConcreteFruits extends Fruits {
private String fruitsName;
public ConcreteFruits(String fruitsName) {
this.fruitsName = fruitsName;
}
@Override
public void buyFruits(User user) {
System.out.println(user.getName()+"购买了"+fruitsName);
}
}
3.创建user用户信息类
public class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
4.创建FruitsFactory水果工厂类
public class FruitsFactory {
private HashMap<String, ConcreteFruits> map = new HashMap<>();
//将内部状态(水果类别)存入map中进行共享
public Fruits getConcreteFruits(String fruitsName){
if(!map.containsKey(fruitsName)){
map.put(fruitsName,new ConcreteFruits(fruitsName));
}
return map.get(fruitsName);
}
//获取水果类别个数
public int getNumber(){
return map.size();
}
}
5.创建Client启动类
public class Client {
public static void main(String[] args) {
FruitsFactory fruitsFactory = new FruitsFactory();
Fruits fruits1 = fruitsFactory.getConcreteFruits("苹果");
fruits1.buyFruits(new User("小天"));
Fruits fruits2 = fruitsFactory.getConcreteFruits("梨");
fruits2.buyFruits(new User("小张"));
Fruits fruits3 = fruitsFactory.getConcreteFruits("苹果");
fruits3.buyFruits(new User("小文"));
Fruits fruits4 = fruitsFactory.getConcreteFruits("橙子");
fruits4.buyFruits(new User("小红"));
Fruits fruits5 = fruitsFactory.getConcreteFruits("苹果");
fruits5.buyFruits(new User("小兰"));
Fruits fruits6 = fruitsFactory.getConcreteFruits("橙子");
fruits6.buyFruits(new User("小兵"));
int number = fruitsFactory.getNumber();
System.out.println("水果类别个数是:"+number+"个");
}
}
5.运行结果
图片.png
网友评论