Design Pattern-flyweight-playball
It's okay on weekends. I have an appointment with my friends to go to the gym (Gymnasium) to play. This gym (Gymnasium) provides a variety of balls. Because we have many players, we chose badminton and pingpangball) for vollyball and other types of balls, we must first fill in the playballlist and then get the ball from the materials department.
Let's take a look at how to implement this process?
1. First, we define an interface class like playball:
Public interface playball {
Public void playball (string ballname); // playball
}
2. playconcreteball is the specific implementation of the playball interface:
Public class playconcreteball implements playball {
Public void playball (string concreteballname ){
System. Out. println ("play" + concreteballname + "! ");
}
}
3. Define the gymnasium (Gymnasium) class:
Public class gymnasium {
Private hashtable playballlist = new hashtable (); // the sports hall selects the ball list based on our needs.
Public playball getplayball (Object key) {// get the ball to be played
Playball = (playball) playballlist. Get (key); // obtain the required Ball Based on the list
If (playball = NULL) {// The ball is not displayed in the list.
Playball = new playconcreteball (); // although there is no such ball in the list, but you still want to play it, you should first get the ball and then fill in the list
Playballlist. Put (Key, playball); // Add the ball to the list.
}
Return playball;
}
Public hashtable getplayballlist () {// get the ball selection list
Return playballlist;
}
}
4. Compile the test class:
Public class test {
Public static void main (string ARGs []) {
Gymnasium = new gymnasium (); // The gymnasium We went
Playball badminton = gymnasium. getplayball ("badminton"); // get Badminton
Playball pingpangball = gymnasium. getplayball (""); // You Want To Get The
Playball vollyball = gymnasium. getplayball ("Volleyball"); // get volleyball
Hashtable selectedballlist = gymnasium. getplayballlist (); // obtain the ball selection list from the device department.
(Playball) selectedballlist. Get ("badminton"). playball ("badminton"); // get Badminton
(Playball) selectedballlist. Get (""). playball (""); // get the
(Playball) selectedballlist. Get ("Volleyball"). playball ("Volleyball"); // get volleyball
}
}
5. Description:
A: flyweight is defined to avoid the overhead of a large number of small classes with the same content (such as memory consumption), so that everyone can share a class (Meta class ).
B: In this example, we can see that by selecting the ball list, we have obtained the required ball type. Therefore, the key point is to fill in the ball selection list. In fact, the focus of Flyweight is here.