How to write a simple factory pattern example

JavaScript Patterns of the Factory mode (Factory) application introduction

Factory mode is also one of the object creation model it is usually in the class or class static method to achieve the construction of the object of a way is to use the new operator, but the use of new is precisely for the realization of the programming will result in a “coupling “The problem of close relationship with specific classes leads to more fragile code lack of flexibility in the complex logic of the project is recommended for interface-oriented programming first look at the simple factory pattern

Code is as follows: Person(nameage){varobj={}objname=nameobjage=agereturnobj} varp=Person(jack)varp=Person(lily)

The difference between writing a class with a constructor approach is that instead of using this, an empty object is constructed each time and then attributes are added to it to create the object not using new but using a function call approach This approach is basically used to replace a class (with the same attributes). objects) and more complex factories can create different types of objects the following example of a fruit factory

The code is as follows: functionBanana(){thisprice=$}functionApple(){thisprice=$}functionOrange(){thisprice=$} //static factory class functionFruit(){}Fruitfactory=function(type){if(!window[type]){return}varfruit=newwindow[type]returnfruit}//make different fruits varbanana=Fruitfactory(Banana)varapple=Fruitfactory(Apple)varorange=Fruitfactory(Orange)

There are three fruit classes BananaAppleOrange and one fruit factory class Fruit. Through the static method factory each time you can create a different fruit class object factory pattern in JavaScript native object Object is also reflected for example

The code is as follows: varobj=Object() num=Object() str=Object(s) boo=Object() false);

The code is as follows: varobj=Object() varorange=Fruitfactory(Apple) varorange=Fruitfactory(Orange)

There are three fruit classes BananaAppleOrange a fruit factory class Fruit. false);

Object is a factory that constructs different objects depending on the parameters obj is an empty object num is an object of type Number str is an object of type String boo is an object of type Boolean jQueryCallbacks is also a factory that every time you call it will return An object with methods such as addremovefire can also be constructed with different properties based on parameters such as “once”, “memory”, etc.

The so-called factory pattern refers to methods that can return an object to the factory. What can we do with this pattern? Suppose I am not satisfied with the existing DOM object inside the method I want to add a custom method called sayHello we can do:

Code is as follows: functionRemouldNodeObj(DomNode){// First determine whether the parameter passed in is a Dom node if( typeofDomNode==”object”&&DomNodenodeType==){DomNodesay=function(){alert(“Hello!!!”) ;}}else{alert(“You passed in an incorrect parameter!”) ;}}

//called this way:windowonload=function(){varoDiv=RemouldNodeObj(documentgetElementById(“test”));//with this step oDiv has the new method sayoDivsay();}< /p>

With the above basis after we come to the realization of the complexity of the function we want to achieve as long as the call through the js to generate a simple form form look at the code:

The code is as follows:<><head><title> JavaScript of the factory model </title&gt ;<scripttype=text/javascript>functionRemouldNodeObj(DOMnode){//First determine if the parameter being passed in is a Dom node if(typeofDOMnode==”object”&& DOMnodenodeType==){DOMnodecreateForm=function(opt){// Below is a big string addition just to put together the form element varoForm=””;oForm+=”<formaction=””+optaction+”””; oForm+=”method=””+(optmethod||GET)+””id=””;oForm+=(optid||””)+”””;oForm+=”class=”page_speeder_503775732″>”;oForm+=”</form&gt ;”;//this here don’t think too hard about who to call pointing to who so this points to oDivthisinnerHTML=oForm;}}else{alert(“Incorrect parameter!”) ;}returnDOMnode;}

//called this waywindowonload=function(){varoDiv=RemouldNodeObj(documentgetElementById(“custom”));oDivcreateForm({ action:indexjspmethod:postid:myForm});}</script></head>

<body><divid=”custom”>###</div></ body></>

lishixin/Article/program/Java/JSP/201311/19973

Write an abstract factory pattern java example out

The factory pattern java example is as follows:

publicinterfaceWork{

voiddoWork();

}

ConcreteProct

publicclassStudentWorkimplementsWork{

publicvoiddoWork(){

System.out.println(“Student doing homework!”) ;

}

}

publicclassTeacherWorkimplementsWork{

publicvoiddoWork(){

System.out.println(“Teacher approves homework!”) )

}

}

Producer

publicinterfaceIWorkFactory{

WorkgetWork();

}

ConcreteCreator

publicclassStudentWorkFactoryimplementsIWorkFactory{

publicWorkgetWork(){

returnnewStudentWork();

}

}

}

< p>publicclassTeacherWorkFactoryimplementsIWorkFactory{

publicWorkgetWork(){

returnnewTeacherWork();

}

}

}

Test

publicclassTest{

publicstaticvoidmain(String[]args){

IWorkFactorystudentWorkFactory= newStudentWorkFactory();

studentWorkFactory.getWork().doWork();

IWorkFactoryteacherWorkFactory= newTeacherWorkFactory();

teacherWorkFactory.getWork().doWork();

}

}

The string is reversed as follows:

publicStringgetReverseStr(Stringstr)

{

StringreverseStr=””;

if(null!=str&&!str.equals(“”))

{

}

}

}

returnreverseStr;

}

Bubbling sort algorithm, smallest to largest

publicint[] sortArr(int[] targetArr){

//Sort from smallest to largest

inttemp=0;

for(inti=0;i<targetArr.length;i++){

for(intj=i;j<targetArr.length;j ++){

if(targetArr[i]>targetArr[j]){

temp=targetArr[i];

targetArr[i]=targetArr[j];

targetArr[j]=temp;

}

}

}

return targetArr;

}

What is the java simple factory pattern

Simple factory pattern of: simple factory pattern is a class creation pattern, also called StaticFactoryMethod pattern. Simple factory pattern is a factory object to determine which instance of the product class is created.

So the simple factory pattern is used in what scenarios, the following is my understanding of the example:

Take the login function, if the application system needs to support a variety of login methods such as: password authentication, domain authentication (password authentication is usually to the database to verify the user, while the domain authentication is the need to verify the user to the Microsoft domain). Then the natural approach is to create a variety of login methods are applicable to the interface, as shown below:

publicinterfaceLogin{

//Login verification

publicbooleanverify(Stringname,Stringpassword);

}

publicclassDomainLoginimplementsLogin{

@Override

publicbooleanverify(Stringname,Stringpassword){

// TODOAuto-generatedmethodstub

/**

*BusinessLogic

*

returntrue;

}

}

publicclassPasswordLoginimplementsLogin{

@Override

publicbooleanverify(Stringname,Stringpassword){

//TODOAuto- generatedmethodstub

/**

*BusinessLogic

*

returntrue;

}

}

We also need a factory class, LoginManager, that creates different caller requirements based on the different login objects and return them. And if it encounters an illegitimate request, it will return a Runtime exception.

publicclassLoginManager{

publicstaticLoginfactory(Stringtype){

if(type.equals(“password”)){

returnnewPasswordLogin();

}elseif(type.equals(“passcode”)){

returnnewDomainLogin();

}else{< /p>

/**

*It would be more appropriate to throw a custom exception here

*/

thrownewRuntimeException(“Login type not found”);

}

}

}

Test class:

publicclassTest{

publicstaticvoidmain(String[]args){

//TODOAuto-generatedmethodstub

StringloginType=”password”;< /p>

Stringname=”name”;

Stringpassword=”password”;

Loginlogin=LoginManager.factory(loginType);

booleanbool= login.verify(name,password);

if(bool){

/**

*BusinessLogic

*

}else{

/**

*BusinessLogic

*

}

}

}

The structure of the Simple Factory Pattern is shown below:

We can envision a real-world scenario, if we take the above Test as a servlet, when the client initiates the login request –> the request is handed over to the server-side Servlet –>Servlet according to the client passed loginType call factory class LoginManager factory () method –>factory () method creates the corresponding login authentication class (DomainLogin or PasswordLogin) based on the loginType parameter and returns –>The login authentication class calls the method verify() to verify that the username and password are correct

If you don’t use the simple factory If you don’t use the simple factory model, then the code for the authentication servlet is as follows (assuming Test is a servlet, and the variables loginType, name, and password represent the parameters passed from the client):

publicclassTest{

publicstaticvoidmain( String[]args){

//TODOAuto-generatedmethodstub

StringloginType=”password”;

Stringname=”name”;

Stringpassword=”password”;

Handling password authentication

if(loginType.equals(“password”)){

PasswordLoginpasswordLogin= newPasswordLogin();

booleanbool=passwordLogin.verify(name,password);

if(bool){

/**

*BusinessLogic

*

} else{

/**

*BusinessLogic

**

}

}

//Handle domain authentication

elseif(loginType.equals(“passcode”)){

DomainLogindomainLogin=newDomainLogin();

booleanbool=domainLogin.verify(name,password);

if(bool){

/**

*Business Logic

*/

}else{

/**

*Business Logic

*/

}

}}else{

/**

*Business Logic

*/

}

}

}

}

Wouldn’t the above code be a pain in the ass. Oh

The book “JAVA and Patterns” uses the java.text.DataFormat class as a typical example of the simple factory pattern narrative.

Benefits of the Simple Factory Pattern

The core of the pattern is the factory class. This class contains the logical judgments necessary to determine which instance of the login authentication class to create at what time, and the caller is relieved of the responsibility of creating the object directly. The simple factory pattern achieves this split of responsibility by eliminating the need to modify the caller when the system introduces a new login method.

Disadvantages of the Simple Factory Pattern

This factory class centralizes all the creation logic, and when there is a complex multi-level hierarchy, all the business logic is implemented in this factory class. Whenever it doesn’t work, the whole system is affected.

Java, Design Patterns, Simple Factory.

The problem is very simple, it is an interface, N concrete classes, and then create an abstract factory to generate different processing classes based on the incoming class name. First look at the project structure diagram:

Common interface:

package pkg1.pkg2;

/**

* Common computational interface

*

* @author

*

*

public interface Common {

// Interface method returns the settlement result

public long calulate(int a, int b, int c);

}

package pkg1;

import pkg1. pkg2.Common;

/**

* Car007 concrete implementation

*

*

* @author

*

*/

public class Car007 implements Common {

public long calulate(int a, int b, int c) {

return a * b / c;

}

}

package pkg1;

import pkg1.pkg2.Common;

/**< /p>

* Plane concrete implementation

*

* @author

*

*

*/

public class Plane implements Common {

public long calulate(int a, int b, int c) {

return a + b + c;

}

}

import pkg1.pkg2.Common;

/**

* Main program application method

*

* @author

* <

*/

public class ComputeTime {

/**

* GetCommonObject

*

* @param clazz

* @return

*/

public static Common getCommonObject(String clazz) {

Common common = null;

// Generate interface object

try {

common = (Common) Class.forName(” pkg1.” + clazz).newInstance();

}

catch (InstantiationException e) {

e.printStackTrace();

}

catch ( IllegalAccessException e) {

e.printStackTrace();

}

catch (ClassNotFoundException e) {

e.printStackTrace();

< p> }

return common;

}

/**

* Calculate the time it takes to run distance

*

* @param distance

* distance

* @param common

* Interface object for calculating speed

* @param a

* @param b

* @param c

* @return

*/

public static double calulate(distance, long common common, int a, int b, int c) {

if ( common ! = null ) { return distance / common.calulate(a, b, c); }

return 0;

}

/**

* Main program methods

*

*

* @param args

*/

public static void main(String[] args) {

if ( args == null || args.length < 4 ) {

System.out.println(“Incorrect number of arguments! Correct format:java ComputeTime XX A B C”);

return;

}

// Get a

int a = Integer.parseInt(args[1]);

// Get b

int b = Integer.parseInt(args[2]);

// Get c

int c = Integer.parseInt(args[3]);

// Calculate the time for 1000 kilometers

System.out.println(args[0]+ “The time required to run 1000 kilometers is: “+calulate(1000, getCommonObject(args[0]), a, b, c)+”hours”);

}

}

The final result of running the program:

Microsoft Windows XP [version 5.1.2600]

(C) Copyright 1985-2001 Microsoft Corp.

E:\>cd E:\workspace\test\bin

E:\workspace\test\bin>java ComputeTime Plane 20 30 40

The time it takes Plane to run 1000 kilometers is: 11.0 hours

E:\workspace\test\bin>java ComputeTime Car007 23 34 45

The time it takes Car007 to run 1000 kilometers is : 58.0 hours

E:\workspace\test\bin>