This article is in the study summary, welcome reprint but please specify Source: http://blog.csdn.net/pistolove/article/details/46400991
This article mainly introduces the simple factory model, mainly through the form of code to show, for programmers I want to watch the code to understand than the document directly and faster.
Simple Factory is the creation mode of a class, also known as the Static Factory method (Factory) mode.
A simple factory model is a factory class that determines which product class to create based on the parameters passed in.
Use the following code to understand the simple factory pattern:
Abstract Product Roles:
Package com.design.factory;//Abstract Product role public interface Car {public void run ();p ublic void Start ();}
Specific product roles:
Package Com.design.factory;public class Benchi implements Car {@Overridepublic void run () {System.err.println ("Benchi Run ");} @Overridepublic void Start () {System.err.println ("Benchi start");}}
Package Com.design.factory;public class Biyadi implements Car {@Overridepublic void run () {System.err.println ("Biyadi Run ");} @Overridepublic void Start () {System.err.println ("Biyadi start");}}
Package Com.design.factory;public class Dazhong implements Car {@Overridepublic void run () {System.err.println ("Dazhong Run ");} @Overridepublic void Start () {System.err.println ("dazhong start");}}
Factory class Roles:
Package Com.design.factory;public class Factory {public static Car getinstance (String clazz) {Car car = null;try {car = (C AR) class.forname ("com.design.factory." + clazz). newinstance (); catch (Exception e) {throw new RuntimeException (e);} return car;}}
Client testing:
Package Com.design.factory;public class Test {public static void main (string[] args) {Car Benchi = factory.getinstance (' Be Nchi "); Benchi.run (); Benchi.start (); System.err.println ("------------"); Car Biyadi = factory.getinstance ("Biyadi"); Biyadi.run (); Biyadi.start (); System.err.println ("------------"); Car Dazhong = factory.getinstance ("Dazhong");D Azhong.run ();D Azhong.start ();}}
Test results:
Benchi Run
Benchi start
------------
Biyadi Run
Biyadi start
------------
Dazhong Run
Dazhong start
Design mode 02_ Simple Factory mode