Design mode Flyweight - playing
Nothing on weekends, gratifying with friends, gymnasium, providing a variety of spheres, because we have more, so choose badminton (pingpangball), vollyball, etc. Squatness, we must first fill in the playballlist, then go to the equipment tie.
Let's take a look at how to achieve this process?
1. We first define a playball (Playball) such an interface class:
Public interface playball {
Public void Playball (String Ballname); // Play the ball
}
2, the playconcreteball) is the specific implementation of the Playball interface:
Public Class PlayCreteball Implements Playball {
Public void playball (string concreteballname) {
System.out.println ("Play" ConcreteballName "!");
}
}
3. Define a gymnasium class:
Public class gymnasium {
Private hashtable playballlist = new hashtable (); // Sports Bottom list according to our needs
Public Playball getPlayball (Object Key) {// Get the ball to play
Playball Playball = (Playball) PlayballList.get (key); // Get the desired ball according to the list
IF (Playball == Null) {// No such ball on the list
Playball = new playconcreteball (); // Although there is no such ball on the list, you still want to play, then you first get this kind of ball, then make a clear order
PlayballList.put (key, playball); // Write this ball into the list
}
Return Playball;
}
Public HashTable getPlayballList () {// Get a list of ball
Return PlayballList;
}
}
4, write test classes:
Public class test {
Public static void main (string args []) {
GYMNASIUM GYMNASIUM = New Gymnasium (); // We go to the gymnasium
Playball Badminton = GYMNASIUM.GETPLAYBALL ("Badminton"); // I want to get badminton
Playball pingpangball = Gymnasium.getPlayball ("Bing Tennis"); // I want to get the talent
Playball Vollyball = Gymnasium.getPlayball ("Volleyball"); // I want to get volleyball
Hashtable selectedballlist = gymnasium.getplayballlist (); // Equipment Department gets a bill of choice
(Playball) SelectedballList.get ("Badminton"). Playball ("Badminton"); // Get Badminton SelectedballList.Get ("Tennis")). Playball ("Bing Tennis"); // Get the talents
(Playball) SelectedballList.get ("Volleyball")). Playball ("Volleyball"); // Get Volleyball
}
}
5. Description:
A: Flyweight Definition: Avoid a large number of small-class overheads (such as spending memory), allowing you to share a class (category).
B: From this example we can see the list of choices, we have obtained the ball, so the key point is to fill in this bill of play, in fact, Flyweight's focus is here.