The idea of the factory mode is: "delay instance creation to subclass"
Java version
Abstract product category:
package Factory;public interface IProduct { void doSomething();}
Class 1:
package Factory;public class Product1 implements IProduct {@Overridepublic void doSomething() {// TODO Auto-generated method stubSystem.out.println("procduct1 do something!");}}
package Factory;public class Product2 implements IProduct {@Overridepublic void doSomething() {// TODO Auto-generated method stubSystem.out.println("procduct2 do something!");}}
Abstract Factory
package Factory;public abstract class AbstractFactory {protected abstract IProduct CreateProduct();public void Operation(){CreateProduct().doSomething();}}
Specific factory Category 1, specific factory Category 2
package Factory;public class ConcreteFactory1 extends AbstractFactory {@Overrideprotected IProduct CreateProduct() {// TODO Auto-generated method stubreturn new Product1();}}
package Factory;public class ConcreteFactory2 extends AbstractFactory {@Overrideprotected IProduct CreateProduct() {// TODO Auto-generated method stubreturn new Product2();}}
Client call:
package Factory;public class MainTest {public static void main(String[] args) {AbstractFactory foctory= new ConcreteFactory1();foctory.Operation();}}
C #, similar to Java, omitted.
JS version:
/* If we want to insert some elements into the webpage, and these element types are not fixed, they may be images or connections, * or even text, according to the definition of the factory mode, we need to define the factory class and the corresponding subclass. * Let's first define the specific implementation of the subclass (that is, the sub-function ): */var page = page | |{}; page. DOM = page. dom | |{}; // process the sub-text page. dom. TEXT = function () {This. insert = function (where) {var TXT = document. createtextnode (this. URL); where. appendchild (txt) ;}// sub-function 2: process the link page. dom. link = function () {This. insert = function (where) {var link = document. createelement ('A'); Link. href = This. URL; Link. appendchild (document. createtextnode (this. URL); where. appendchild (Link) ;};}; // subfunction 3: process the image page. dom. image = function () {This. insert = function (where) {var im = document. createelement ('img '); Im. src = This. URL; where. appendchild (IM) ;};}; // factory method page. dom. factory = function (type) {return new page. dom [type];} // call page. dom. client = function () {var o = page. dom. factory ('link'); O. url = 'HTTP: // www.cnblogs.com '; O. insert (document. body );}