一、享元模式
1.享元模式定义:为了避免大量拥有相同内容的小类重复创建,而使大家共享一个类的模式。Flyweight享元设计模式实质是运用一个简单工厂方法模式,外加一个单类模式实现细粒度原件的共享。
2.享元模式的UML
3.享元模式示例
class Book{
private String title;
private float price;
private Author author;
public String getTitle(){
return title;
}
public float getPrice(){
return price;
}
public Author getAuthor(){
return author;
}
}
//将Author作者类设计为可共享的享元
class Author{
//内部状态
private String name;
public String getName(){
return name;
}
public Author(String name){
this.name = name;
}
}
//享元工厂
public class AuthorFactory{
private static Map<String, Author> authors = new HashMap<String, Author>();
public static Author getAuthor(String name){
Author author = authors.get(name);
if(author == null){
author = new Author(name);
authors.put(name, author);
}
return author;
}
}