码迷,mamicode.com
首页 > 其他好文 > 详细

抽象工厂学习

时间:2015-11-16 12:42:05      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

Abstract Factory
    1. Intent
    <1> Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
    <2> A hierarchy that encapsulates: many possible "platforms", and the construction of a suite of "products".
    <3> The new operator considered harmful.
    2. Problem
       If an application is to be portable, it needs to encapsulate platform dependencies. These "platforms" might include: windowing system, operating system, database, etc. Too often, this encapsulatation is not engineered in advance, and lots of #ifdef case statements with options for all currently supported platforms begin to procreate like rabbits throughout the code.
    3. Discussion
    <1> Provide a level of indirection that abstracts the creation of families of related or dependent objects without directly specifying their concrete classes. The "factory" object has the responsibility for providing creation services for the entire platform family. Clients never create platform objects directly, they ask the factory to do that for them.
    <2> This mechanism makes exchanging product families easy because the specific class of the factory object appears only once in the application - where it is instantiated. The application can wholesale replace the entire family of products simply by instantiating a different concrete instance of the abstract factory.
    <3> Because the service provided by the factory object is so pervasive, it is routinely implemented as a Singleton.    
    4. Structure
       The Abstract Factory defines a Factory Method per product. Each Factory Method encapsulates the new operator and the concrete, platform-specific, product classes. Each "platform" is then modeled with a Factory derived class.
技术分享
    5. Example
       The purpose of the Abstract Factory is to provide an interface for creating families of related objects, without specifying concrete classes. This pattern is found in the sheet metal stamping equipment used in the manufacture of Japanese automobiles. The stamping equipment is an Abstract Factory which creates auto body parts. The same machinery is used to stamp right hand doors, left hand doors, right front fenders, left front fenders, hoods, etc. for different models of cars. Through the use of rollers to change the stamping dies, the concrete classes produced by the machinery can be changed within three minutes.
技术分享
    6. Check list
    <1> Decide if "platform independence" and creation services are the current source of pain.
    <2> Map out a matrix of "platforms" versus "products".
    <3> Define a factory interface that consists of a factory method per product.
    <4> Define a factory derived class for each platform that encapsulates all references to the new operator.
    <5> The client should retire all references to new, and use the factory methods to create the product objects.
    7. Rules of thumb
    <1> Sometimes creational patterns are competitors: there are cases when either Prototype or Abstract Factory could be used profitably. At other times they are complementary: Abstract Factory might store a set of Prototypes from which to clone and return product objects, Builder can use one of the other patterns to implement which components get built. Abstract Factory, Builder, and Prototype can use Singleton in their implementation.
    <2> Abstract Factory, Builder, and Prototype define a factory object that‘s responsible for knowing and creating the class of product objects, and make it a parameter of the system. Abstract Factory has the factory object producing objects of several classes. Builder has the factory object building a complex product incrementally using a correspondingly complex protocol. Prototype has the factory object (aka prototype) building a product by copying a prototype object.
    <3> Abstract Factory classes are often implemented with Factory Methods, but they can also be implemented using Prototype.
    <4> Abstract Factory can be used as an alternative to Facade to hide platform-specific classes.
    <5> Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
    <6> Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
    8. Abstract Factory in Java
public class FactoryFmProto
{
    static class Expression
    {
        protected String str;
        public Expression(String s)
        {
            str = s;
        }
        public Expression cloan()
        {
            return null;
        }
        public String toString()
        {
            return str;
        }
    }

    static abstract class Factory
    {
        protected Expression prototype = null;
        public Expression makePhrase()
        {
            return prototype.cloan();
        }
        public abstract Expression makeCompromise();
        public abstract Expression makeGrade();
    }

    static class PCFactory extends Factory
    {
        public PCFactory()
        {
            prototype = new PCPhrase();
        }
        public Expression makeCompromise()
        {
            return new Expression("\"do it your way, any way, or no way\"");
        }
        public Expression makeGrade()
        {
            return new Expression("\"you pass, self-esteem intact\"");
        }
    }

    static class NotPCFactory extends Factory
    {
        public NotPCFactory()
        {
            prototype = new NotPCPhrase();
        }
        public Expression makeCompromise()
        {
            return new Expression("\"my way, or the highway\"");
        }
        public Expression makeGrade()
        {
            return new Expression("\"take test, deal with the results\"");
        }
    }

    public static void main(String[] args)
    {
        Factory factory;
        if (args.length > 0)
            factory = new PCFactory();
        else
            factory = new NotPCFactory();
        for (int i = 0; i < 3; i++)
            System.out.print(factory.makePhrase() + "  ");
        System.out.println();
        System.out.println(factory.makeCompromise());
        System.out.println(factory.makeGrade());
    }

    static class PCPhrase extends Expression
    {
        static String[] list = 
        {
            "\"animal companion\"", "\"vertically challenged\"", 
                "\"factually inaccurate\"", "\"chronologically gifted\""
        };
        private static int next = 0;
        public PCPhrase()
        {
            super(list[next]);
            next = (next + 1) % list.length;
        }
        public Expression cloan()
        {
            return new PCPhrase();
        }
    }

    static class NotPCPhrase extends Expression
    {
        private static String[] list = 
        {
            "\"pet\"", "\"short\"", "\"lie\"", "\"old\""
        };
        private static int next = 0;
        public NotPCPhrase()
        {
            super(list[next]);
            next = (next + 1) % list.length;
        }
        public Expression cloan()
        {
            return new NotPCPhrase();
        }
    }
}



运行结果:

D:\Java\patterns> java FactoryFmProto
"short"  "lie"  "old"
"my way, or the highway"
"take test, deal with the results"

D:\Java\patterns> java FactoryFmProto 1
"vertically challenged"  "factually inaccurate"  "chronologically gifted"
"do it your way, any way, or no way"
"you pass, self-esteem intact"



抽象工厂学习

标签:

原文地址:http://my.oschina.net/u/1989867/blog/530771

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!