Learning Design Patterns Series - Simple Factory pattern (Java)

A simple factory pattern profile is a simple factory pattern to create class-based model, also known as the static factory method model. Specifically defined by a class responsible for creating instances of other classes, an instance is created usually have a common parent.
For example:

The first step: one apple and banana class category, which have the same put off the method get (), code as follows:

package com.wds.simplefactory;

/**
 *  Banana class
 * 2010-6-26  In the afternoon  09:46:59
 */
public class Banana{

        /**
         *  Acquisition
         * 2010-6-26  In the afternoon  09:47:16
         */
        public void get(){
                System.out.println(" Acquisition of bananas  ");
        }
}

Apple class as follows:

/**
 *  Caoguo class
 * 2010-6-26  In the afternoon  09:45:41
 */
public class Apple{

        /**
         *  Acquisition of apples
         * 2010-6-26  In the afternoon  09:46:20
         */
        public void get(){
                System.out.println(" Acquisition of apples  ");
        }

}

Main class MainClass:

/**
 *  The main class
 * 2010-6-26  In the afternoon  09:45:29
 */
public class MainClass {

        /**
         * 2010-6-26  In the afternoon  09:45:29
         * @param args
         */
        public static void main(String[] args) {
                /*
                 *  Instantiate a  Apple
                 */
                Apple apple=new Apple();

                /*
                 *  Instantiate a  Banana
                 */
                Banana banana=new Banana();

                apple.get();
                banana.get();
              }
}

Step two: former first completed a preliminary operations, but the apples and bananas in the two classes Du a pick of Method get (),, so we collected from two classes in a Fruit interfaces, code:

/**
 * Fruit Interface
 * 2010-6-26  In the afternoon  09:50:57
 */
public interface Fruit {

        /**
         *  The removal of
         */
        public void get();

}

Then apple and banana class implements Fruit class interface code as follows:

/** * Apple class * 2010-6-26 In the afternoon 09:45:41 */ public class Apple implements Fruit{ /** * Acquisition of apples * 2010-6-26 In the afternoon 09:46:20 */ public void get(){ System.out.println(" Acquisition of apples "); } }
/**
 *  Banana class
 * 2010-6-26  In the afternoon  09:46:59
 */
public class Banana implements Fruit{

        /**
         *  Acquisition
         * 2010-6-26  In the afternoon  09:47:16
         */
        public void get(){
                System.out.println(" Acquisition of bananas  ");
        }
}

Master class on instances of Apple and Banana change the code as follows:

/**
 *  The main class
 * 2010-6-26  In the afternoon  09:45:29
 */
public class MainClass {

        /**
         * 2010-6-26  In the afternoon  09:45:29
         * @param args
         */
        public static void main(String[] args) {

                // Use the interface to instantiate a  Apple
                Fruit apple=new Apple();
                // Use the interface to instantiate a  Banana
                Fruit banana=new Banana();
                apple.get();
                banana.get();

                }
}

The third step: Apple and Banana You as a common interface, and simple factory pattern, defined by a class devoted to Fuzechuangjian instances of other classes, were created in the Shi Li usually share common parent class. So we create a fruit factory class to create Apple and Banana FruitFactory the two classes.

FruitFactory code:

/**
 *  Fruit factory class
 * 2010-6-26  In the afternoon  09:53:48
 */
public class FruitFactory {

        /**
         *  Obtain an instance of the Apple class
         */
        public static Fruit getApple(){
                return new Apple();
        }

        /**
         *  Obtain an instance of a Banana
         * 2010-6-26  In the afternoon  09:54:47
         * @return
         */
        public static Fruit getBanan(){
                return new Banana();
        }
}

Then there is the main class with the changes in the code below

MainClass

/**
 *  The main class
 * 2010-6-26  In the afternoon  09:45:29
 */
public class MainClass {

        /**
         * 2010-6-26  In the afternoon  09:45:29
         * @param args
         */
        public static void main(String[] args) {
                                Fruit apple=FruitFactory.getApple();
                Fruit banana=FruitFactory.getBanan();
                apple.get();
                banana.get();
               }
}

The fourth step, as in the factory class, is a get method, just return the contents are different, we change another way, only get one way, according to different parameters decided to return to the class different, FruitFactory code:

/**
 *  Fruit factory class
 * 2010-6-26  In the afternoon  09:53:48
 */
public class FruitFactory {
        /**
         * get Method, get all the product object
         *  Exception I to ignore, when we write added
         */
        public static Fruit getFruit(String type){
                if(type.equalsIgnoreCase("apple")){
                        return Apple.class.newInstance();
                }else if(type.equalsIgnoreCase("banana")){
                        return Banana.class.newInstance();
                }else{
                        System.out.println("can not find class");
                        return null;
                }
}

The fifth step, because the factory class to judge fruit more statements, we created for a more general way, the code is as follows:

/**
 *  Fruit factory class
 * 2010-6-26  In the afternoon  09:53:48
 */
public class FruitFactory {
        /**
         * get Method, get all the product object
         * @throws ClassNotFoundException
         * @throws IllegalAccessException
         * @throws InstantiationException
         */
        public static Fruit getFruit(String type) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
                                // Here, the reason why plus  com.wds.simplefacotry, Because Apple class and  Banana Class and package with a FruitFactory class below  , The package name is  com.wds.simplefactory
                Class fruit=Class.forName("com.wds.simplefactory."+type);
                //System.out.println(FruitFactory.class.getResource(""));
                //Class fruit=Class.forName(FruitFactory.class.getClassLoader().getResource("")+type);
                return (Fruit) fruit.newInstance();

        }
}

Thus, the factory class has been completed, then the main class code change, change as follows:

/**
 *  The main class
 * 2010-6-26  In the afternoon  09:45:29
 */
public class MainClass {

        /**
         * 2010-6-26  In the afternoon  09:45:29
         * @param args
         */
        public static void main(String[] args) {
                try {
                               Fruit banana=FruitFactory.getFruit("Banana");
                                       Fruit apple = FruitFactory.getFruit("Apple");
                        apple.get();
                        banana.get();
                } catch (InstantiationException e) {
                        e.printStackTrace();
                } catch (IllegalAccessException e) {
                        e.printStackTrace();
                } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                }
}
分类:Java 时间:2010-06-27 人气:182
分享到:
blog comments powered by Disqus

相关文章

  • public static void main (String args []) parameters 2010-05-15

    String args [] is the main function of main parameters, namely array of strings. Using eclipse in the editing, right-click to run the Java files in the Run As option, select Run Configurations. Main class in the Project and complete the project, resp ...

  • Why public static void main (String args []){} 2010-11-06

    main () is a Java program entry, program execution is the beginning of this entry. Class is a class member, main () method must be public members. So that it can be called in the execution environment. main () method does not produce the object can b

  • Use AIDL (Android Interface Description Language) design and use of remote interface 2010-09-28

    Directory 1 Use AIDL (AndRoid Interface Description Language) design and use of remote interface 1.1 IPC implementation using AIDL 1.1.1 Creating a AIDL file 1.1.2 implement the interface Public interface to the client 1.1.3 1.1.4 the value of using the p

  • Calls from non-public classes public class main method 2010-09-27

    class testArray{ public static void main(String args[]){ for(String s : args){ //args Accept from DynamicArray class from a string System.out.println(s); } } } public class DynamicArray{ public static void main(String args[]){ testArray.main(new String[]{

  • 浅析C#中的Main(String[] args)参数输入问题 2014-07-20

    本篇文章主要是对C#中的Main(String[] args)参数输入问题进行了详细的介绍,需要的朋友可以过来参考下,希望对大家有所帮助 指定相关的测试代码 首先,写一个用于测试的关于Main(String[] args)参数输入有关的代码类,如下: using System; public class Hello { public static void Main(String[] args) { switch (args[0]) { case "老板": Console.WriteLine(

  • [Zhuantie] design of Android's user interface (b) 2010-11-13

    In the article, related to a number of resource files, direct view that is res directory of the directories and files, commonly used are: • res / drawable / used to store image files • res / layout / used to store the layout definition file • res / v

  • How the eclipse of the main the String [] args parameter passed, and then export it 2010-12-26

    How the eclipse of the main the String [] args parameter passed, and then export it? In the Run menu to find Open Run dialog opens Select Java Application in the program need to run Select the Arguments Tab Enter the parameters in the Programe Argume

  • String [] args = new String [] {sql.toString ()} 2011-06-29

    In this problem StringBuffer sql = new StringBuffer (); Which sql.toString results: 'Test User 1', 'male' String [] args = new String [] {sql.toString ()} args.length 1 results Obviously not what we need. Note: new String []{"",

  • C / C + + & Java string comparison splicing efficiency (lower) [content over the length is truncated to complete documentation and source code can be downloaded] 2011-01-10

    C / C + + string stitching test run results: Release version. TEST_TIME: 90000 C language memcpy append Used: 0 ms. string length: 630000 std:: string + = operator Used: 15 ms. string length: 630000 std:: string append Used: 16 ms. string length: 630

  • Java and Design Patterns - chapter 9 Interface Segregation Principle 2010-03-22

    Chapter IX Interface Segregation Principle Interface segregation principle is about: using multiple specialized interface than using a single interface to better overall. In other words, from a customer perspective: a class is dependent on another cl ...

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.336 (s). 12 q(s)