The factory approach to Java design patterns

Source: Internet
Author: User


That process we use the program to express, first define a human collective name:

Public interface Human {//First define what is human//people are happy, will laugh, originally wanted to use smile to say, think about laugh more appropriate, for a long time did not laugh, public void laugh ();//Human will cry, Stands for pain public void Cry ();//human will speak public void talk ();}

Then define the specific race:

public class Yellowhuman implements Human {public void Cry () {System.out.println ("Yellow race will Cry");} public void Laugh () {System.out.println ("Yellow race will laugh and be happy!") ");} public void Talk () {System.out.println ("The yellow race speaks, and generally says double-byte");}  }

public class Whitehuman implements Human {public void Cry () {System.out.println ("White race Will Cry");} public void Laugh () {System.out.println ("White race laughs, aggressive laughter"); public void Talk () {System.out.println ("The white race speaks, generally but single-byte! ");}}

public class Blackhuman implements Human {public void Cry () {System.out.println ("Black Will Cry");} public void Laugh () {System.out.println ("Black will Laugh");} public void Talk () {System.out.println ("Black can speak, ordinary people do not understand");}}

/*** * * Today talk about the story of Nu wa making man , the synopsis of this story is this: * A long time ago, Pangu opened up the world, with the body to create stars, mountains and trees, heaven and earth a prosperous * one day, Nu wa Nether walked a, hey! Too lonely, too lonely, not a will laugh, will cry, can talk about things * how to do? Do not worry, Nu WA, Immortal Ah, made out, and then pinch the mud, put gossip stove (later this became white Venus of the baby) in the roast, so there is a person: * We put this production process with Java program Show: */public class Humanfactory {//set an oven, The mud plugs in, the man comes out, this is too advanced public static Human Createhuman (Class c) {Human human=null;//define a type of human try {Human = (Human) Class.forName (C.getname ()). Newinstance (); Produce a race} catch (Instantiationexception e) {//If you don't say a personal color, you can't bake it, you have to be white and black, and you talk. System.out.println ("The color of the race must be specified");} catch ( Illegalaccessexception e) {//definition of the race there is a problem, it is not baked out, this is ... SYSTEM.OUT.PRINTLN ("Ethnographic definition Error! ");} catch (ClassNotFoundException e) {//You casually say a personal kind, where do I make it for you?! System.out.println ("Bastard, you don't specify the race to find!") ");} return human;}} 
public class Nvwa {public static void main (string[] args) {////NU WA first made man, test nature, less build point, insufficient heat, defective product System.out.println ("----------- -The first group of people to be created is this: White-----------------"); Human Whitehuman = Humanfactory.createhuman (Whitehuman.class); Whitehuman.cry (); Whitehuman.laugh (); WhiteHuman.talk ();//Nu WA The second time to create a person, the heat added sufficient points, and then a defective, black System.out.println ("\ n------------made the second group of people is this: Black-----------------"); Human Blackhuman = Humanfactory.createhuman (Blackhuman.class); Blackhuman.cry (); Blackhuman.laugh (); BlackHuman.talk ();///The third group of people, this time to grasp the right, yellow race (do not write yellow people, lest cause ambiguity), note: RB people do not belong to this column System.out.println ("\n\ N------------made the third group of people like this: the Yellow race-----------------"); Human Yellowhuman = Humanfactory.createhuman (Yellowhuman.class); Yellowhuman.cry (); Yellowhuman.laugh (); Yellowhuman.talk ()}}

So this world is lively, people also have, but this creates too tired, the immortal also will be tired, how to do? The immortal wants to be
: I stuffed a group of mud, randomly out of a group of people, tube he is black, white, yellow people, as long as the person is (you see, the gods are stealing
Lazy, not to mention we are people), first modify the class diagram:


Then see our program changes, first modify the Humanfactory.java, add the Createhuman () method: Package Com.cbf4life;import Java.util.list;import Java.util.random;public class Humanfactory {//fix an oven, the mud plugs in, people come out, this is too advanced public static Human Createhuman (class C) {Human Human=null; Defines a type of human try {human = (human) class.forname (C.getname ()). newinstance ();//produce a race} catch (Instantiationexception e) {/ /If you do not say the color of the individual, you can not bake, to white black, you speak only good roast System.out.println ("must specify the color of the Race");} catch (Illegalaccessexception e) {//Definition of the race is problematic, it is not baked out, this is ... SYSTEM.OUT.PRINTLN ("Ethnographic definition Error! ");} catch (ClassNotFoundException e) {//You casually say a personal kind, where do I make it for you?! System.out.println ("Bastard, you don't specify the race to find!") ");} return human;} Nu wa angry, put a group of mud into gossip stove, hey produce what race on what race public static Human Createhuman () {Human human=null;//define a type of human//the first is to obtain how many implementation classes, How many individual species list<class> concretehumanlist =classutils.getallclassbyinterface (human.class); Define how many races//gossip stove themselves began to want to burn out what people on what people random random = new random (); int rand = Random.nextint (Concretehumanlist.size ()); human = Createhuman (Concretehumanlist.get (Rand)); return human;}}

Then see how Nu WA is doing:

public class Nvwa {public static void main (string[] args) {////NU WA first made man, test nature, less build point, insufficient heat, defective product System.out.println ("----------- -The first group of people to be created is this: White-----------------"); Human Whitehuman = Humanfactory.createhuman (Whitehuman.class); Whitehuman.cry (); Whitehuman.laugh (); WhiteHuman.talk ();//Nu WA The second time to create a person, the heat added sufficient points, and then a defective, black System.out.println ("\ n------------made the second group of people is this: Black-----------------"); Human Blackhuman = Humanfactory.createhuman (Blackhuman.class); Blackhuman.cry (); Blackhuman.laugh (); BlackHuman.talk ();///The third group of people, this time to grasp the right, yellow race (do not write yellow people, lest cause ambiguity), note: RB people do not belong to this column System.out.println ("\n\ N------------made the third group of people like this: the Yellow race-----------------"); Human Yellowhuman = Humanfactory.createhuman (Yellowhuman.class); Yellowhuman.cry (); Yellowhuman.laugh (); Yellowhuman.talk ();//Nu WA irritability, Love is what race is what race, burn bar for (int i=0;i<10000000000;i++) {System.out.println ("\n\ n------------randomly produced races-----------------"+i); Human Human = Humanfactory.createhuman (); Human.cry (); Human.laugh (); Human.talk ();}}}
public class Classutils {//to an interface that returns all implementation class public static list<class> Getallclassbyinterface (Class C) for this interface {list< class> returnclasslist = new arraylist<class> (); Returns the result//if it is not an interface, do not process if (C.isinterface ()) {String PackageName = C.getpackage (). GetName ();//get current package name try {list< class> Allclass = getclasses (PackageName); Get all classes under the current package and sub-packages//Determine if it is the same interface for (int i=0;i<allclass.size (); i++) {if (C.isassignablefrom (Allclass.get (i))) {// The judgment is not an interface if (!c.equals (Allclass.get (i))) {//itself not added to Returnclasslist.add (Allclass.get (i));}}}} catch (ClassNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}} return returnclasslist;} Finding all classes from a package, you cannot find the private static list<class> getclasses (String packagename) in the jar package throws ClassNotFoundException, IOException {ClassLoader ClassLoader = Thread.CurrentThread (). Getcontextclassloader (); String path = Packagename.replace ('. ', '/'); enumeration<url> resources = classloader.getresources (path); List<file> dirs = new Arraylist<file> (); while (Resources.hasmoreelements ()) {URL resource = resources.nextelement ();d Irs.add (new File (Resource.getfile ()));} arraylist<class> classes = new arraylist<class> (); for (File directory:dirs) {Classes.addall (findclasses ( Directory, PackageName));} return classes;} private static list<class> findclasses (File directory, String PackageName) throws ClassNotFoundException {List <Class> classes = new arraylist<class> (); if (!directory.exists ()) {return classes;} file[] files = directory.listfiles (); for (File file:files) {if (File.isdirectory ()) {Assert!file.getname (). Contains (". "); Classes.addall (findclasses (file, PackageName +". "+file.getname ()));} else if (File.getname (). EndsWith (". Class")) {Classes.add (Class.forName (PackageName + ') +file.getname (). substring (0 , File.getname (). Length ()-6)));}} return classes;}}

The factory method model also has a very important application, that is, deferred initiation (lazy initialization), what is deferred initialization?
When an object is initialized, it is not released, and when it is used again, it is not initialized again, directly from the memory to get it,

How to achieve it, very simple, see examples:

public class Humanfactory {//define a map, the initialized Human object is placed here private static hashmap<string,human> humans = new HashMap <String,Human> ();//Set an oven, the mud is stuffed in, people come out, this is too advanced public static Human Createhuman (Class c) {Human human=null; Defines a type of human try {//If there is a map, it is removed directly from, without initializing if (Humans.containskey (C.getsimplename ())) {human = Humans.get (c.getsimplename ());} Else{human = (human) class.forname (C.getname ()). newinstance ();//Put in Map Humans.put (C.getsimplename (), human);}} catch (Instantiationexception e) {//If you do not say a personal color, you can not bake, to white black, you speak only good roast System.out.println ("must specify the color of the Race");} catch ( Illegalaccessexception e) {//A certain definition of the race has a problem, it is not baked out, it is ... SYSTEM.OUT.PRINTLN ("Ethnographic definition Error! ");} catch (ClassNotFoundException e) {//You casually say a personal kind, where do I make it for you?! System.out.println ("Bastard, you don't specify the race to find!") ");} return human;}}
You want to connect the hardware, or to initialize a class, you need to prepare to compare multiple conditions (parameters), which can be a good way to reduce the complexity of the project.


The factory approach to Java 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.