Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

java - Good pattern for creating an object that supports interning?

I need a Class that supports interning, like Java's String class. When creating an instance of the Class it should return a pre-existing reference if a reference with the same parameters already exists. Otherwise it should return a new reference. Such that:

Foo a = new Foo(5);
Foo b = new Foo(5);
Foo c = new Foo(6);
a == b
a != c

1) Is it the job of a factory to maintain the table of pre-existing objects, or is the table generally just a static variable within the class itself?

2) What is the table of pre-existing objects? Is it a Set of objects you search through every time an instance is requested, or is it a Map where keys are objects and values are parameters?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Two things come to my mind

  1. Flyweight Pattern

  2. Guava's ComputingMap


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...