common patterns for Java
Adapter mode
1 PackageCom.huawei;2 3 ImportJava.io.BufferedReader;4 Importjava.io.IOException;5 ImportJava.io.InputStreamReader;6 7 Importjava.util.Observable;8 ImportJava.util.Observer;9 Ten InterfaceWindow One { A Public voidopen (); - Public voidclose (); - Public voidactive (); the } - - Abstract classWindowadapterImplementsWindow - { + Public voidopen () {} - Public voidclose () {} + Public voidactive () {} A } at - classWindowimplextendsWindowadapter - { - Public voidOpen () - { -System.out.println ("Open ..."); in } - Public voidClose () to { +System.out.println ("Close ..."); - } the Public voidActive () * { $System.out.println ("Active ...");Panax Notoginseng } - } the + A Public classFornumber the { + Public Static voidMain (String args[]) - { $Window win =NewWindowimpl (); $ Win.open (); - win.close (); - } the}View Code
Factory mode
1 PackageCom.huawei;2 3 ImportJava.io.BufferedReader;4 Importjava.io.IOException;5 ImportJava.io.InputStreamReader;6 7 Importjava.util.Observable;8 ImportJava.util.Observer;9 Ten InterfaceFruit One { A Public voideat (); - } - the classAppleImplementsFruit - { - - Public voidEat () + { -System.out.println ("Eat Apple"); + } A at } - - - classOrangeImplementsFruit - { - Public voidEat () in { -System.out.println ("Eat Orange"); to } + } - //Define Factory the classFactory * { $ Public StaticFruit getinstance (String className)Panax Notoginseng { -Fruit f =NULL; the if("Apple". Equals (className)) + { Af =NewApple (); the } + - if("Orange". Equals (className)) $ { $f =NewOrange (); - } - the returnF; - }Wuyi } the - Public classFornumber Wu { - Public Static voidMain (String args[]) About { $Fruit f =NULL;//Defining Interface Objects -f =NewFactory (). getinstance ("Apple")); - f.eat (); - } A}View Code
Common patterns in Java learning---