Ho usato molti degli altri che sono già stati menzionati (Singleton, Factory, Builder, Command, Strategy, ecc ...)
Uno che non ho ancora visto menzionato è Flyweight, che tendo a usare molto. Ho fornito un'implementazione di esempio di seguito:
/**
* Flyweight class representing OCR digits.
*
* @author matt
*
*/
public class Digit {
/** Static flyweight map containing Digits which have been encountered. **/
private static Map digits = new HashMap();
/** The block of text representing Digit. **/
private String blockRep = null;
/** A map representing acceptable blocks of characters and the string representation of their
* numerical equivalents.
*/
public static final Map VALID_DIGITS;
/** Enum of valid digits. **/
public static enum DigitRep {
ZERO ( " _ \n" +
"| |\n" +
"|_|" ),
ONE ( " \n" +
" |\n" +
" |" ),
TWO ( " _ \n" +
" _|\n" +
"|_ " ),
THREE ( " _ \n" +
" _|\n" +
" _|" ),
FOUR ( " \n" +
"|_|\n" +
" |" ),
FIVE ( " _ \n" +
"|_ \n" +
" _|" ),
SIX ( " _ \n" +
"|_ \n" +
"|_|" ),
SEVEN ( " _ \n" +
" |\n" +
" |" ),
EIGHT ( " _ \n" +
"|_|\n" +
"|_|" ),
NINE ( " _ \n" +
"|_|\n" +
" _|" );
private String blockRep;
DigitRep(String blockRep) {
this.blockRep = blockRep;
}
@Override
public String toString() {
return blockRep;
}
}
static {
/* Initialize the map of acceptable character blocks. */
Map tmpMap = new HashMap();
tmpMap.put( DigitRep.ZERO.toString(), "0");
tmpMap.put( DigitRep.ONE.toString(), "1");
tmpMap.put( DigitRep.TWO.toString(), "2");
tmpMap.put( DigitRep.THREE.toString(), "3");
tmpMap.put( DigitRep.FOUR.toString(), "4");
tmpMap.put( DigitRep.FIVE.toString(), "5");
tmpMap.put( DigitRep.SIX.toString(), "6");
tmpMap.put( DigitRep.SEVEN.toString(), "7");
tmpMap.put( DigitRep.EIGHT.toString(), "8");
tmpMap.put( DigitRep.NINE.toString(), "9");
VALID_DIGITS = Collections.unmodifiableMap(tmpMap);
}
/**
* Private constructor to enforce flyweight/factory pattern.
*
* @param blockRep
*/
private Digit(String blockRep) {
this.blockRep = blockRep;
}
/**
* Flyweight factory method to create a Digit object from the "block"
* representation of the digit.
* @param blockRep The "block" representation of a digit. Should look
* something like:
* " _ \n"
* "|_|\n"
* "|_|"
* @return A flyweight Digit object representing the digit.
*/
public static synchronized Digit getDigit(String blockRep) {
Digit digit = digits.get(blockRep);
if(digit == null) {
digit = new Digit(blockRep);
digits.put(blockRep, digit);
}
return digit;
}
/**
* Determines whether or not the digit is valid.
* @return true if the digit is valid, else false.
*/
public boolean isValid() {
return VALID_DIGITS.containsKey(blockRep);
}
/**
* Accessor method to get the block representation of this digit.
*
* @return
*/
public String getBlockRep() {
return blockRep;
}
@Override
public String toString() {
return VALID_DIGITS.containsKey(blockRep) ? VALID_DIGITS.get(blockRep) : "?";
}
}