享元模式 Flyweight Pattern

一、什么是享元模式
Flyweight模式也叫享元模式,是构造型模式之一,它通过与其他类似对象共享数据来减小内存占用。

二、享元模式的结构
see the picture



三、享元模式的角色和职责

抽象享元角色:

所有具体享元类的父类,规定一些需要实现的公共接口。

具体享元角色:

抽象享元角色的具体实现类,并实现了抽象享元角色规定的方法。

享元工厂角色:

负责创建和管理享元角色。

MyCharacter.java
public class MyCharacter { 
    private char mychar; 
 
    public MyCharacter(char mychar) { 
        this.mychar = mychar; 
    } 
 
    public void display() { 
        System.out.println(mychar); 
    } 
}
MyCharacterFactory.java
import java.util.HashMap; 
import java.util.Map; 
 
 
public class MyCharacterFactory { 
    private Map<Character,MyCharacter> pool; 
 
    public MyCharacterFactory() { 
        pool = new HashMap<Character,MyCharacter>(); 
    } 
 
    public MyCharacter getMyCharacter(Character character) { 
        MyCharacter myChar = pool.get(character); 
        if(myChar == null) { 
            myChar = new MyCharacter(character); 
            pool.put(character, myChar); 
        } 
        return myChar; 
    } 
}
MainClass.java
public class MainClass { 
	 
    public static void main(String[] args) { 
//      MyCharacter myChar1 = new MyCharacter('a'); 
//      MyCharacter myChar2 = new MyCharacter('b'); 
//      MyCharacter myChar3 = new MyCharacter('a'); 
//      MyCharacter myChar4 = new MyCharacter('d'); 
// 
//      myChar1.display(); 
//      myChar2.display(); 
//      myChar3.display(); 
//      myChar4.display(); 
// 
//      if(myChar1 == myChar3) { 
//          System.out.println("true"); 
//      } else { 
//          System.out.println("false"); 
//      } 
        //1.创建MyCharacter工厂 
        MyCharacterFactory factory = new MyCharacterFactory(); 
 
        //2.从工厂中取出相应的MyCharacter 
        MyCharacter myChar1 = factory.getMyCharacter('a'); 
        MyCharacter myChar2 = factory.getMyCharacter('b'); 
        MyCharacter myChar3 = factory.getMyCharacter('a'); 
        MyCharacter myChar4 = factory.getMyCharacter('d'); 
 
        myChar1.display(); 
        myChar2.display(); 
        myChar3.display(); 
        myChar4.display(); 
 
        if(myChar1 == myChar3) { 
            System.out.println("true"); 
        } else { 
            System.out.println("false"); 
        } 
    } 
 
}




你可能感兴趣的:(String,null,Class,import,character)