The _java of notes and the arrangement of design patterns

Source: Internet
Author: User

Design Pattern Classification: Create Type: New method, instantiate the structure type: The combination of the class, apply the behavior: the operation of the method must master the design pattern: factory, template, Singleton, command, adapter, proxy interface defined first, then implement abstract class and interface: Light with inheritance will cause, the parent class A change, the subclass will have to change, code can be used to use the interface subclass must override all methods of the parent class, the code can not reuse the reflection mechanism: the reflection mechanism is in the running state, for any class, can know all the properties and methods of the class, for any one object, can call any of its methods and properties    This dynamic acquisition of information and the ability to dynamically invoke the object's methods is called the reflection mechanism of the Java language The reflection mechanism mainly provides the following functions: To judge the class of any object at runtime, to construct an object of any class at run time, to judge the member variables and methods of any class at run time; A method that invokes any object at run time, and generates a dynamic proxy. Get the full package name and class name from an objectNewclass name (). GetClass (). GetName () Gets the class Class.forName ("Net.xsoftlab.baike.TestReflect");Newtestreflect (). GetClass (); Testreflect.classgets the parent class of an object and implements the interface to get the parent class<?> ParentClass =Clazz.getsuperclass (); Get all the Interfaces class<?> intes[] =clazz.getinterfaces (); Instantiate object instantiation of a class by reflection mechanism the default constructor method user User=(User) class1.newinstance () obtains all constructors using constructors to assign values constructor<?> cons[] =class1.getconstructors (); Gets the parameter of the constructor cons[i].getparametertypes (); Gets all the properties of this class field[] field=clazz.getdeclaredfields (); permission modifierintModifier=field[i].getmodifiers (); String Priv=modifier.tostring (MO); attribute type class<?> type =Field[i].gettype (); Gets the implemented interface or parent class Property field[] filed1=clazz.getfields (); Get all methods of class method method[]=clazz.getmethods (); Get method return value type class<?> ReturnType =Method[i].getreturntype (); Get method Parameter class<?> para[] =method[i].getparametertypes (); Get method modifierinttemp =method[i].getmodifiers (); Get method Exception type class<?> exce[] =method[i].getexceptiontypes (); Invoke method of a class by reflection mechanism= Clazz.getmethod ("Reflect1"); Method.invoke (Clazz.newinstance ()); Manipulating the properties of a class by reflection mechanism can directlyPrivateThe Property Assignment Field field= Clazz.getdeclaredfield ("Proprety"); Field.setaccessible (true); Field.set (obj,"Java Reflection mechanism"); Holds a string object in the ArrayList of the generic type integer Public Static voidMain (string[] args)throwsException {ArrayList<Integer> list =NewArraylist<integer>(); Method Method= List.getclass (). GetMethod ("Add", Object.class); Method.invoke (list,"Java reflection mechanism instance. "); System.out.println (List.get (0)); } modifies the value of the array by reflection Array.set (temp,0, 100); Modify the size of the array by reflection mechanism System.arraycopy (old array name,0, new array name, 0, the old number of team leader degree); Design pattern: A scenario that a predecessor programmer gives when solving a specific program development problem. A singleton pattern: only one copy of the construction method for an object of a certain type in a program privatization creates a static, unique object that provides a public static method to return a unique object ( Whether the broken object has been instantiated) Public classsingletonclass{Private StaticSingletonclass instance=NULL;PrivateSingletonclass () {} Public Static   synchronizedSingletonclass getinstance () {if(instance==NULL) {instance=NewSingletonclass (); }            returninstance; }} recursive call: Public classtest{ Public Static voidMain (string[] args) {System.out.println (5)); }         Public Static intMethodintN) {            if(n = = 1){                return1; }Else{                returnN * Method (n-1); }}}: Provide a proxy for other objects, and to control the Access Proxy pattern of this object in different scenarios, will have to establish a different interface, resulting in code can not be reused Java provides a reflection mechanism called dynamic Proxy in the dynamic agent mechanism of Java, there are two important classes or interfaces , one is the only method of Invocationhandler (Interface) Invocationhandler This interface Invoke method: Object Invoke (Object proxy, method method, Object[] args)throwsThrowableproxy: Refers to the real object that we represent. Method: Refers to the method object that we are going to call the real object. Args: Refers to a parameter that is accepted when a method of a real object is called and the other is a proxy (Class) The function of the proxy class is to create a class that dynamically creates a proxy object. Public StaticObject newproxyinstance (ClassLoader loader, Class<?>[] interfaces, Invocationhandler h)throwsIllegalargumentexceptionloader: A ClassLoader object that defines which ClassLoader object to load the generated proxy object interfaces: An array of interface objects , which means I'm going to provide a set of interfaces to the object I need to proxy, and if I provide a set of interfaces to it, then the proxy object declares that it implements the interface (polymorphic) so I can invoke the method in this set of Interfaces H: A Invocationhandler object, It means that when I call the method, the dynamic proxy object will be associated to the proxy instance on the Invocationhandler object: the proxy public interface: Public InterfaceReadinterface { Public voidreader ();} By the agent (customer): Public classPersonImplementsreadinterface{@Override Public voidReader () {System.out.println ("---------start reading now---------"); System.out.println ("---------read a chapter---------"); System.out.println ("---------read another chapter--------"); System.out.println ("---------This chapter is wonderful---------"); System.out.println ("---------read it all day---------"); System.out.println ("---------Finished reading---------"); }} Agent: Public classProxyreadImplementsinvocationhandler{PrivateObject subject;  PublicProxyread (Object subject) { This. Subject =subject; }     PublicObject Createproxy () {returnproxy.newproxyinstance (Subject.getclass (). getClassLoader (), Subject.getclass (). Getinterfaces (), This); } @Override Publicobject Invoke (Object proxy, Method method, object[] args)throwsThrowable {Longbegin=System.currenttimemillis (); System.out.println ("--------Universal proxy class start doing things----------"); Object obj=Method.invoke (subject, args); System.out.println ("--------the Universal proxy class to do things----------"); LongEnd=System.currenttimemillis (); System.out.println ("Execution Program spent" + (End-begin) *1.0/1000+ "seconds"); returnobj; }} Test class: Public classTest { Public Static voidMain (string[] args) {proxyread PR=NewProxyread (NewPerson ()); Readinterface Read=(Readinterface) pr.createproxy ();    Read.reader (); }} applies the reflection mechanism to Factory modeInterfaceFruit { Public Abstract voideat ();}classAppleImplementsFruit { Public voideat () {System.out.println ("Apple"); }}classOrangeImplementsFruit { Public voideat () {System.out.println ("Orange"); }}classFactory { Public StaticFruit getinstance (String ClassName) {fruit F=NULL; Try{f=(Fruit) class.forname (ClassName). newinstance (); } Catch(Exception e) {e.printstacktrace (); }        returnF; }} Policy mode: Set the variable capability as an interface, in the public parent class, set as a variable, and call its methods, another subclass implements the interface, and assigns an abstract parent class to an interface variable when it inherits the abstract parent class: Public Abstract classDuck {Privateflyable flyable =NULL;  Public voidsetflyable (flyable flyable) { This. flyable =flyable; }     Public voidFly () {//flying object. Fly ();Flyable.fly (); }     Public voidswim () {System.out.println ("Floating ..."); } Public Abstract voiddispaly ();} Interface: Public Interfaceflyable { Public voidfly ();} Interface implementation: Public classRocketflyImplementsflyable{@Override Public voidFly () {System.out.println ("Fly with the Rockets ..."); }} Public classWingflyImplementsflyable {@Override Public voidFly () {System.out.println ("Fly with your own wings ..."); }} inherits the abstract class: Public classRedduckextendsduck{ PublicRedduck () {Super. setflyable (Newwingfly ()); } @Override Public voiddispaly () {System.out.println ("The red-headed duck, the head is red"); }} Test: Public classTest { Public Static voidMain (string[] args) {test3 (); }     Public Static voidtest3 () {Duck Duck=NewRedduck (); //Transsexual Squeak//rocket tied up, take a look at the flight effectDuck.setflyable (Newrocketfly ());        Duck.dispaly ();        Duck.swim ();        Duck.fly (); }} template mode: Public  classbenz{ Public  voidstart () {System.out.println ("Mercedes Benz Boot");} Public voidTrunleft () {System.out.println ("Mercedes Benz Left Turn");} Public voidalerm () {System.out.println ("The Mercedes-Benz car Beeps");} Public voidStop () {System.out.println ("Mercedes Benz Car Parking");}} Public  classbmw{ Public  voidstart () {System.out.println ("BMW car Start");} Public voidTrunleft () {System.out.println ("BMW turning Left");} Public voidalerm () {System.out.println ("BMW rings a Whistle");} Public voidStop () {System.out.println ("BMW car Parking");}} Template: Public  Abstract classcar{ Public  Abstract voidStart () Public  Abstract voidtrunleft (); Public  Abstract  voidalerm (); PublicAbstract  voidstop (); Public  voidbegin () { This. Start ();  This. Trunleft ();  This. Alerm ();  This. Stop ();}}

The _java of notes and the arrangement of design patterns

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.