Design mode Factory

xiaoxiao2021-04-04  272

Definition: Provides an interface to create an object.

Why? The factory model is our most common mode. The famous JIVE Forum uses a large number of factory models, and the factory model can be said to be everywhere in the Java program system.

Why is the factory model so common? Because the plant mode is equivalent to the new instance object, we often generate instance objects according to class Class, such as A a = new a () factory model is also used to create instance objects, so you will have multiple minds when New. Can I consider practical factory models, although doing this, may do more work, but will give you more scalability and minimal modifications.

We use class SAMPLE as an example, if we want to create instance objects of Sample:

Sample sample = new sample ();

However, the actual situation is, usually we have to do some initialization work when you create a Sample instance, such as assigning the query database.

First of all, we think that you can use the Sample constructor, which generates an instance to be written:

Sample sample = new sample; parameter;

However, if the initialization work made when creating a Sample instance is not like assigning a simple matter, it may be a long code. If you also write into the constructor, then your code is ugly (just need refactor reach).

Why is it difficult to say that beginners may not have this feeling, we analyze the following, if it is a long code, it means that there are many work to do, put a lot of work into a method, equivalent to putting a lot of eggs In a basket, it is very dangerous, which is also a principle of Java-oriented objects. Object-oriented package (encapsulation) and dispatch tell us, try to assign a long code to a "cutting" into each section, will each Segment is then "package" (reducing the coupling between segments and segments), which will disperse the risk, if you need to modify, as long as you change each paragraph, you will not happen.

In this example, first, we need to separate the work of the creation instance and the use of the instance, that is, let the large amount of initialization required for the creation instance from separating from the Sample constructor.

At this time, we need Factory factory model to generate an object, and you cannot use the simple new sample (parameter) above. Also, if Sample has inherits such as mysample, according to the interface programming, we need to abstract Sample into an interface. Now Sample is an interface, there are two subclass mysample and hissample. We have to instantiate them, as follows:

Sample mysample = new mysample (); sample hissample = new Hissample ();

As the project is in-depth, Sample may "give birth to a lot of son", then we have to instantiate these sons, even worse, may also modify the previous code: Joining the instance of the son later. This is unavoidable in traditional programs.

But if you have a conscious use of factory models, these troubles are there.

Factory method You will establish a factory specializing in the production of Sample instances:

Public class factory {

Public Static Sample Creator (INT which) {

// getClass generates SAMPLE usually uses a dynamic class load to load classes. IF (Which == 1) Return new Sample (); else if (which == 2) Return new sampleb ();

}

} So in your program, if you want to instantiate Sample, use

Sample Samplea = Factory.creator (1); This, throughout the case, the concrete subclass of SAMPLE does not involve the package effect, and the opportunity to reduce the error modification can be reduced. This principle can be used very popular: it is specific to do The more you get, the easier it is wrong. This person who has made specific work is deeply appreciated. On the contrary, the higher the official, the more abstract, the more abstract, the less wrong, the less, it seems to be Can you realize the truth from your programming? Hehe.

Use the factory method to pay attention to several roles, first you want to define the product interface, as the sample above, the product interface has the implementation class, such as SAMPLEA, after another, with a Factory class, used to generate product Sample, as shown below, The homemost side is the object of the production:

Further, a little more complicated is to expand at the factory class, and the factory class also has inherits its implementation of CONCRETEFACTeFactory.

Abstract factory factory models are: Factory Method Abstract Factory (ABSTRACT FACTORY).

These two patterns differ in the complexity of the need to create objects. If we create objects, it is more complicated, as in the factory method, you create an object Sample, if we have new product interface Sample2.

Here, it is assumed: Sample has two Concrete class Samplea and Samleb, and Sample2 also has two Concrete class Sample2a and Sampleb2.

Then, we will turn the Factory in the above example into an abstract class, and the common partial package is in an abstract class. Different parts use subclass implementation, the following is to expand the Factory in the above example into an abstract factory:

Public Abstract Class Factory {

Public Abstract Sample Creator ();

Public Abstract Sample2 Creat (String Name);

}

Public class SimpleFactory Extends Factory {

Public Sample Creator () {......... Return New SampleA}

Public Sample2 Creat (String Name) {......... Return New Sample2a}

}

Public class bombfactory extends factory {

Public Sample Creator () {... return new sampleb}

Public Sample2 Creator (String Name) {... return new sample2b}

}

From the above, two factories have produced a set of Sample and Sample2, maybe you will have questions, why can't I use two factory methods to produce SAMPLE and SAMPLE2?

The abstract factory has another key point because there is a connection between the SimpleFactory, the production of SAMPLE and production of SAMPLE2, so it is necessary to bundle these two methods in a class, this factory class has its own characteristics, perhaps The manufacturing process is unified, such as: the manufacturing process is relatively simple, so the name is SimpleFactory.

In practical applications, the factory method is used more, and it is combined with the dynamic loader.

Example

In the first Singleton mode we discussed in the previous Singleton mode, we will discuss its factory model now: public abstract class forumfactory {

private static Object initLock = new Object (); private static String className = "com.jivesoftware.forum.database.DbForumFactory"; private static ForumFactory factory = null; public static ForumFactory getInstance (Authorization authorization) {// If no valid authorization passed IN, RETURN NULL. IF (authorization == null) {return null;} // The following uses Singleton Dynamic Mode IF (Factory == Null) {synchronized (factory == null) {... ...

Try {// Dynamic Reset Class C = Class.Forname (ClassName); Factory = (forumFactory) c.newinstance ();} catch (exception e) {return null;}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}

// Now, return Proxy. Used to limit the authorization to the Forum access Return New ForumFactoryProxy (Authorization, Factory, Factory.getPermission (Authorization));}

/ / Really create a method of inheriting the subclass of ForumFactory. Public Abstract Forum Createforum (String Name, String Description) Throws UnauthorizedException, forumalReadyexistSexception;

....

}

Because the current jive is to store content data such as the forum post through the database system, if you want to change to implement the file system, this factory method ForumFactory provides a dynamic interface:

Private static string classname = "com.jivesoftware.forum.database.dbforumfactory";

You can use your own development to create Forum instead of com.jivesoftware.forum.database.dbforumFactory.

In a total of three modes in the above code, in addition to the factory model, there is a Singleton monetary mode, as well as the Proxy mode, the Proxy mode is mainly used to authorize the user's access to the Forum, because there are two people: one Is a registered user is a tourist GUEST, then the corresponding permissions are different, and this permission is throughout the system, so establish a proxy, similar gateway concept, can achieve this effect very well.

Take a look at the CatalogDaFactory in the Java pet shop:

Public class catalogdaofactory {

/ **

* This method makes a special subclass to implement DAO mode. * The specific subclass definition is in the J2EE deployment descriptor. * /

Public static catalogdao getdao () throws catalogdaosystem {

Catalogdao catdao = null;

Try {

InitialContext IC = New InitialContext (); // Dynamic Load Catalog_DAO_CLASS / / You can define your own Catalog_DAO_CLASS, so that the huge change of the system is completed without changing too much code //. String classname = (string) Ic.lookup (JNDINAMES.CATALOG_DAO_CLASS);

CATDAO = (CatalogDao) Class.Forname (classname) .newinstance ();

} catch (namingexception ne) {

Throw New CatalogDaosystemsException ("CatalogDaFactory.getdao: Namingexception while getting dao type: / n" ne.getMessage ());

} catch (exception se) {

Throw new catalogdaosystemsException ("CatalogDaFactory.GetDao: Exception While Getting Dao Type: / N" se.getMessage ());

}

Return CATDAO;

}

}

CatalogDaofactory is a typical factory method. Implement subclasses, name your subclass name to the Catalog_DAO_CLASS variable.

It can be seen that the factory method does provide a very flexible dynamic expansion mechanism for the system structure, as long as we replace the specific factory method, there may no need to change the system elsewhere, it is possible to change the system function.

转载请注明原文地址:https://www.9cbs.com/read-131813.html

New Post(0)