Design Pattern proxy-buy tickets
This year's New Year's Eve is very good. I won 100 yuan in cards. I smiled proudly and I laughed proudly. In short, the word "awesome ". I have never won a card game in past years! I am happy to return home. Before I can report my situation, my wife gave me a sentence: "My brother is going back to Shanghai. You can buy a ticket ." Although I was not happy, my face was very happy. I immediately said in a firm tone: "Please rest assured that you can complete the task !". Guarantee is guaranteed, but tickets for the Chinese New Year are really hard to buy. After some setbacks (whining), I had to go to the ticket dealer (proxy ).
When talking about agency, you may not be familiar with it. In fact, many agents in the society can also be understood as agents. To put it bluntly, they will help you with your work and take the agency fee.
1. Here, we first define the ticket purchase activity as an interface (buyticket) class:
Public interface buyticket {
Public void buyticket ();
}
2. We will implement these two interfaces below
A: normal ticket activity (normalbuyticket) class:
Public class normalbuyticket implements buyticket {
Public void buyticket (){
System. Out. println ("buy a train ticket! ");
}
}
B: proxybuyticket:
// When you cannot directly access the normalbuyticket object, you must use a proxy object.
Public class proxybuyticket implements buyticket {
Private normalbuyticket;
Public void buyticket (){
If (normalbuyticket = NULL ){
Normalbuyticket = new normalbuyticket ();
}
Normalbuyticket. buyticket ();
Getmoney ();
}
Public void getmoney (){
System. Out. println ("Get proxy fee! ");
}
}
3. Compile the test class:
Public class test {
Public static void main (string ARGs []) {
Buyticket = new proxybuyticket ();
Buyticket. buyticket ();
}
}
4. Description:
A: Definition: provides a proxy for other objects to control access to this object. That is to say, when we cannot directly access the object we want to access, we must access it through a proxy object.
B: In this example, I want to buy a ticket, but when I can't buy a ticket directly, I have to buy it through the ticket dealer. Everyone knows this.
5. Postscript:
Finally, I got a ticket to Shanghai through the ticket dealer. My wife was very happy and said that I was very competent, but I paid 100 yuan in agency fee. Should I cry or laugh, but think about it again: "I spent 100 yuan to let my wife praise me and say that I am very competent and good. What do you mean! Hey ".