Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Factory (object-oriented programming)

From Wikipedia, the free encyclopedia
Object that creates other objects
"Factory pattern" redirects here. For the GoF design patterns using factories, seefactory method pattern andabstract factory pattern.
Factory Method in LePUS3

Inobject-oriented programming, afactory is anobject forcreating other objects; formally, it is afunction ormethod that returns objects of a varying prototype orclass[1] from some method call, which is assumed to benew.[a] More broadly, a subroutine that returns anew object may be referred to as afactory, as infactory method orfactory function. The factory pattern is the basis for a number of relatedsoftware design patterns.

Motive

[edit]

Inclass-based programming, a factory is anabstraction of aconstructor of a class, while inprototype-based programming a factory is an abstraction of a prototype object. A constructor is concrete in that it creates objects asinstances of one class, and by a specified process (class instantiation), while a factory can create objects by instantiating various classes, or by using other allocation means, such as anobject pool. A prototype object is concrete in that it is used to create objects by beingcloned, while a factory can create objects by cloning various prototypes, or by other allocation means.

A factory may be implemented in various ways. Most often it is implemented as a method, in which case it is called afactory method. Sometimes it is implemented as a function, in which case it is called afactory function. In some languages, constructors are factories. However, in most languages they are not, and constructors are invoked in a way that is idiomatic to the language, such as by using the keywordnew, while a factory has no special status and is invoked via an ordinary method call or function call. In these languages, a factory is an abstraction of a constructor, but not strictly a generalization, as constructors are not factories.

Terminology

[edit]

Terminology differs as to whether the concept of a factory is a design pattern – inDesign Patterns there is nofactory pattern, but instead two patterns (factory method pattern andabstract factory pattern) that use factories. Some sources refer to the concept as thefactory pattern,[2][3] while others consider the concept aprogramming idiom,[4] reserving the termfactory pattern orfactory patterns to more complicated patterns that use factories, most often the factory method pattern; in this context, the concept of a factory may be referred to as asimple factory.[4] In other contexts, particularly thePython language, the termfactory is used, as in this article.[5] More broadly,factory may be applied not just to an object that returns objects from some method call, but to asubroutine that returns objects, as in afactory function (even if functions are not objects) orfactory method.[6] Because in many languages factories are invoked by calling a method, the general concept of a factory is often confused with the specificfactory method pattern design pattern.

Use

[edit]

OOP providespolymorphism on objectuse bymethod dispatch, formallysubtype polymorphism viasingle dispatch determined by the type of the object on which the method is called. However, this does not work for constructors, as constructorscreate an object of some type, rather thanuse an existing object. More concretely, when a constructor is called, there is no object yet on which to dispatch.[b]

Using factories instead of constructors or prototypes allows one to use polymorphism for object creation, not only object use. Specifically, using factories providesencapsulation, and means the code is not tied to specific classes or objects, and thus the class hierarchy or prototypes can be changed orrefactored without needing to change code that uses them – they abstract from the class hierarchy or prototypes.

More technically, in languages where factories generalize constructors, factories can usually be used anywhere constructors can be,[c] meaning that interfaces that accept a constructor can also in general accept a factory – usually one only need something that creates an object, rather than needing to specify a class and instantiation.

For example, in Python, thecollections.defaultdict class[7] has a constructor which creates an object of typedefaultdict[d] whose default values are produced by invoking a factory. The factory is passed as an argument to the constructor, and can be a constructor, or any thing that behaves like a constructor – acallable object that returns an object, i.e., a factory. For example, using thelist constructor for lists:

# collections.defaultdict([default_factory[, ...]])d=defaultdict(list)

Object creation

[edit]

Factory objects are used in situations where getting hold of an object of a particular kind is a more complex process than simply creating a new object, notably if complex allocation or initialization is desired. Some of the processes required in the creation of an object include determining which object to create, managing the lifetime of the object, and managing specialized build-up and tear-down concerns of the object. The factory object might decide to create the object'sclass (if applicable) dynamically, return it from anobject pool, do complex configuration on the object, or other things. Similarly, using this definition, asingleton implemented by thesingleton pattern is a formal factory – it returns an object, but does not create new objects beyond the one instance.

Examples

[edit]

The simplest example of a factory is a simple factory function, which just invokes a constructor and returns the result. InPython, a factory functionf that instantiates a classA can be implemented as:

deff():returnA()

A simple factory function implementing the singleton pattern is:

deff():iff.objisNone:f.obj=A()returnf.objf.obj=None

This will create an object when first called, and always return the same object thereafter.

Syntax

[edit]

Factories may be invoked in various ways, most often a method call (afactory method), sometimes by being called as a function if the factory is a callable object (afactory function). In some languages constructors and factories have identical syntax, while in others constructors have special syntax. In languages where constructors and factories have identical syntax, like Python,Perl,Ruby,Object Pascal, andF#,[e] constructors can be transparently replaced by factories. In languages where they differ, one must distinguish them in interfaces, and switching between constructors and factories requires changing the calls.

Semantics

[edit]

In languages where objects aredynamically allocated, as in Java or Python, factories are semantically equivalent to constructors. However, in languages such asC++ that allow some objects to be statically allocated, factories are different from constructors for statically allocated classes, as the latter can have memory allocation determined at compile time, while allocation of the return values of factories must be determined at run time. If a constructor can be passed as an argument to a function, then invocation of the constructor and allocation of the return value must be done dynamically at run time, and thus have similar or identical semantics to invoking a factory.

Design patterns

[edit]
Further information:Creational pattern

Factories are used in variousdesign patterns, specifically increational patterns such as theDesign pattern object library. Specific recipes have been developed to implement them in many languages. For example, severalGoF patterns, like theFactory method pattern, theBuilder or even theSingleton are implementations of this concept. TheAbstract factory pattern instead is a method to build collections of factories.

In some design patterns, a factory object has amethod for every kind of object it can create. These methods optionally acceptparameters defining how the object is created, and then return the created object.

Applications

[edit]

Factory objects are common inwidget toolkits andsoftware frameworks wherelibrary code needs to create objects of types which may be subclassed by applications using the framework. They are also used intest-driven development to allow classes to be put under test.[8]

Factories determine theconcrete type ofobject to be created, and it is here that the object is created. As the factory only returns an abstract interface to the object, the client code does not know, and is unburdened by, the concrete type of the object which was just created. However, the type of a concrete object is known by the abstract factory. In particular, this means:

  • The client code has no knowledge whatsoever of the concretedata type, not needing to include anyheader files orclassdeclarations relating to the concrete type. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through theirabstract interface.
  • Adding new concrete types is done by modifying the client code to use a different factory, a modification which is typically one line in one file. This is significantly easier than modifying the client code to instantiate a new type, which would require changingevery location in the code where a new object is created.

Applicability

[edit]

Factories can be used when:

  1. Creating an object makes reuse impossible without significant duplication of code.
  2. Creating an object requires access to information or resources that should not be contained within the composing class.
  3. Managing the lifetime of generated objects must be centralized to ensure consistent behavior within an application.

Factories, specifically factory methods, are common inwidget toolkits andsoftware frameworks, where library code needs to create objects of types that may be subclassed by applications using the framework.

Parallel class hierarchies often require objects from one hierarchy to be able to create appropriate objects from another.

Factory methods are used intest-driven development to allow classes to be put under test.[9] If such a classFoo creates another objectDangerous that can't be put under automatedunit tests (perhaps it communicates with a production database that isn't always available), then the creation ofDangerous objects is placed in thevirtual factory methodcreateDangerous in classFoo. For testing,TestFoo (a subclass ofFoo) is then created, with the virtual factory methodcreateDangerous overridden to create and returnFakeDangerous, afake object. Unit tests then useTestFoo to test the functionality ofFoo without incurring the side effect of using a realDangerous object.

Benefits and variants

[edit]

Besides use in design patterns, factories, especially factory methods, have various benefits and variations.

Descriptive names

[edit]

A factory method has a distinct name. In many object-oriented languages, constructors must have the same name as the class they are in, which can lead to ambiguity if there is more than one way to create an object (seeoverloading). Factory methods have no such constraint and can have descriptive names; these are sometimes known asalternative constructors. As an example, whencomplex numbers are created from two real numbers the real numbers can be interpreted as Cartesian or polar coordinates, but using factory methods, the meaning is clear, as illustrated by the following example inC#.

publicclassComplex{publicdouble_real;publicdouble_imaginary;publicstaticComplexFromCartesian(doublereal,doubleimaginary){returnnewComplex(real,imaginary);}publicstaticComplexFromPolar(doublemodulus,doubleangle){returnnewComplex(modulus*Math.Cos(angle),modulus*Math.Sin(angle));}privateComplex(doublereal,doubleimaginary){this._real=real;this._imaginary=imaginary;}}Complexproduct=Complex.FromPolar(1,Math.PI);

When factory methods are used for disambiguation like this, the raw constructors are often made private to force clients to use the factory methods.

Encapsulation

[edit]

Factory methods encapsulate the creation of objects.This can be useful if the creation process is very complex; for example, if it depends on settings in configuration files or on user input.

Consider as an example a program that readsimage files. The program supports different image formats, represented by a reader class for each format.

Each time the program reads an image, it needs to create a reader of the appropriate type based on some information in the file. This logic can be encapsulated in a factory method. This approach has also been referred to as the Simple Factory.

Java

[edit]
Further information:Java (programming language)
publicclassImageReaderFactory{publicstaticImageReadercreateImageReader(ImageInputStreamProcessoriisp){if(iisp.isGIF()){returnnewGifReader(iisp.getInputStream());}elseif(iisp.isJPEG()){returnnewJpegReader(iisp.getInputStream());}else{thrownewIllegalArgumentException("Unknown image type.");}}}

PHP

[edit]
Further information:PHP
classFactory{publicstaticfunctionbuild(string$type):FormatInterface{$class="Format".$type;returnnew$class;}}interfaceFormatInterface{}classFormatStringimplementsFormatInterface{}classFormatNumberimplementsFormatInterface{}try{$string=Factory::build("String");}catch(Error$e){echo$e->getMessage();}try{$number=Factory::build("Number");}catch(Error$e){echo$e->getMessage();}

Limits

[edit]

There are three limits associated with the use of the factory method. The first involvesrefactoring existing code; the other two involves extending a class.

  • The first limit is that refactoring an existing class to use factories breaks existing clients. For example, if class Complex were a standard class, it might have many clients with code like:
    Complexc=newComplex(-1,0);
Once it is realized that two different factories are needed, the class is changed (to the code shownearlier). But since the constructor is now private, the existing client code no longer compiles.
  • The second limit is that, since the pattern relies on using a private constructor, the class cannot be extended. Any subclass must invoke the inherited constructor, but this cannot be done if that constructor is private.
  • The third limit is that, if the class were to be extended (e.g., by making the constructor protected—this is risky but feasible), the subclass must provide its own re-implementation of all factory methods with exactly the same signatures. For example, if classStrangeComplex extendsComplex, then unlessStrangeComplex provides its own version of all factory methods, the call
    StrangeComplex.FromPolar(1,Math.Pi);
    will yield an instance ofComplex (the superclass) rather than the expected instance of the subclass. Thereflective programming (reflection) features of some languages can avoid this issue.

All three problems could be alleviated by altering the underlying programming language to make factories first-class class members (see alsoVirtual class).[10]

Notes

[edit]
  1. ^Interface-wise, any object that returns an object can be used as a factory, but semantically a factory returns either a newly created object, like a classinstance or copy of a prototype, or an object that looks new, like a re-initialized object from an object pool.
  2. ^In languages where constructors are methods on a class object (class methods), there is an existing object, and constructors are special cases of factory methods, with polymorphic creation being a special case of polymorphic method dispatch. In other languages there is a sharp distinction between constructors and methods.
  3. ^Constructors can be used anywhere factories can, since they are a special case.
  4. ^This class is a subclass ofdict, the built-in Python implementation of mappings or dictionaries.
  5. ^If optional keywordnew is omitted.

References

[edit]
  1. ^Gamma, Erich (1994).Design Patterns. Addison-Wesley. pp. 18–19.ISBN 9780321700698.
  2. ^Factory Pattern,OODesign.com
  3. ^Factory Pattern,WikiWikiWeb
  4. ^abChapter 4. The Factory Pattern: Baking with OO GoodnessArchived 2017-03-11 at theWayback Machine:The Simple Factory definedArchived 2014-02-19 at theWayback Machine
  5. ^30.8 Classes Are Objects: Generic Object Factories,Learning Python, by Mark Lutz, 4th edition, O'Reilly Media, Inc.,ISBN 978-0-596-15806-4
  6. ^Factory Method,WikiWikiWeb
  7. ^defaultdict objects
  8. ^Feathers, Michael (October 2004).Working Effectively with Legacy Code. Upper Saddle River, New Jersey: Prentice Hall Professional Technical Reference.ISBN 978-0-13-117705-5.
  9. ^Feathers, Michael (October 2004).Working Effectively with Legacy Code. Upper Saddle River, NJ: Prentice Hall Professional Technical Reference.ISBN 978-0-13-117705-5.
  10. ^Agerbo, Ellen; Cornils, Aino (1998). "How to preserve the benefits of design patterns".Conference on Object Oriented Programming Systems Languages and Applications. Vancouver, British Columbia, Canada: ACM:134–143.ISBN 1-58113-005-8.
Retrieved from "https://en.wikipedia.org/w/index.php?title=Factory_(object-oriented_programming)&oldid=1249490663"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp