Computer Science
Factory Pattern
The Factory Pattern is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. This pattern is useful when you need to create objects that share common characteristics, but have different implementations.
Written by Perlego with AI-assistance
Related key terms
1 of 5
10 Key excerpts on "Factory Pattern"
- eBook - ePub
- Dorothy R. Kirk(Author)
- 2022(Publication Date)
- Packt Publishing(Publisher)
Each full program example can be found in the GitHub repository under the appropriate chapter heading (subdirectory) in a file that corresponds to the chapter number, followed by a dash, followed by the example number in the chapter at hand. For example, the first full program in this chapter can be found in the subdirectory Chapter17 in a file named Chp17-Ex1.cpp under the aforementioned GitHub directory. The CiA video for this chapter can be viewed at: https://bit.ly/3QOmCC1. Understanding the Factory Method pattern The Factory Pattern, or Factory Method pattern, is a creational design pattern that allows the creation of objects without needing to specify the exact (derived) class that will be instantiated. A Factory Method pattern provides an interface for creating an object, yet allows details within the creation method to decide which (derived) class to instantiate. A Factory Method pattern is also known as a virtual constructor. Much as a virtual destructor has the specific destructor (which is the entry point of the destruction sequence) determined at runtime through dynamic binding, the concept of a virtual constructor is such that the desired object to instantiate is uniformly determined at runtime. We cannot always anticipate the specific mix of related derived class objects needed in an application. A Factory Method (or virtual constructor) can create, upon request, an instance of one of many related derived class types, based on the input provided. A derived class object will be returned as its base class type by the Factory Method, allowing objects to be both created and stored more generically. Polymorphic operations can be applied to the newly created (upcasted) instances, allowing relevant derived class behaviors to shine through. A Factory Method promotes loose coupling with client code by removing the need to bind specific derived class types in the client code itself - eBook - ePub
Practical Design Patterns for Java Developers
Hone your software design skills by implementing popular design patterns in Java
- Miroslav Wengner(Author)
- 2023(Publication Date)
- Packt Publishing(Publisher)
It means that in the coming decades, we can expect an increase in pressure to improve the efficiency of software and design. To gain clarity of the application logic, it needs to be crystal clear how the application works, and moreover, how the application feeds the key JVM areas, namely, the method stack and heap followed by the thread utilization through the stack areas (as shown previously in Figure 2.2). Due to the current software applications’ trends focused on mapping, transforming, or managing a large amount of data, creational design patterns are worthwhile to study, understand, and learn how to deal with common scenarios. Although the time of the Gang of Four (GoF) book has passed, evolution is inevitable and the challenges remain. In many cases, with proper abstraction, the initial creational design patterns are applicable. Creating objects and class instances, and filling out the intended parts of the JVM, may drastically influence the computation and performance costs, as well as enforce business logic clarity. In the next section, we discuss different possibilities for object creation. We will also consider the recently added Java syntactic features and possibilities, which should reduce the source code’s verbosity. Let us start with one of the most common patterns. Creating objects based on input with the factory method pattern The primary purpose of this pattern is to centralize the class’s instantiation of a specific type. The pattern leaves the decision to create the exact class type up to the client at runtime. The factory method design pattern was described in the GoF’s book. Motivation The factory method pattern enforces the separation of code and its responsibility for creating new instances of the class, that is, such a method provides the expected result. The factory hides an application class hierarchy based on a generics abstraction and introduces a common interface - No longer available |Learn more
Hands-On Design Patterns with Java
Learn design patterns that enable the building of large-scale software architectures
- Dr. Edward Lavieri(Author)
- 2019(Publication Date)
- Packt Publishing(Publisher)
The six creational design patterns presented in this chapter can be grouped into two subcategories—those that focus on classes and those that focus on objects. The following table details these subcategories:Object Scope Class Scope Abstract Factory Pattern Factory Pattern Builder pattern Simple Factory Pattern Prototype pattern Singleton pattern The creational design patterns listed in the preceding table are detailed in the remaining sections of this chapter. They are presented in alphabetical order to illustrate that one is not more important than the others.Passage contains an image
Understanding the abstract factory design pattern
Before we look at the abstract factory design pattern, let's first review the term abstract and how it applies to Java classes and the programs we develop.The term abstract refers to something not having a definitive existence. In Java, abstract classes cannot be instantiated, but they can be inherited. Let's consider an example of an abstract Grandmother class that is extended by a Mother class. A third class, Daughter, is used to house the main() method. Here is the code for the Grandmother class:abstract class Grandmother { // Constructor Grandmother() { System.out .println("Grandmother constructor executed." ); }}Next, we have the Mother class, which extends Grandmother and has its own constructor method:public class Mother extends Grandmother { // Constructor Mother() { System.out .println("Mother constructor executed." ); }}The final class in this example is the Daughter class. Here is the code:public class Daughter { public static void main(String[] args) { Mother mom = new Mother(); }}When the application is run, the following results are provided in the console window: Abstract class sample program output As you can see in the following screenshot, if we try to instantiate the Grandmother class, we are presented with the error that the class is abstract and cannot be instantiated: Error in abstract class instantiationThe abstract factory design pattern creates an interface that is used to create multiple objects without knowledge of the concrete class. A concrete class in Java is a non-abstract class that implements all of the methods in its hierarchy. This is a high-powered demonstration of encapsulation. This design pattern allows us to change implementations without changing source code. - eBook - ePub
Software Engineering Design
Theory and Practice
- Carlos Otero(Author)
- 2016(Publication Date)
- Auerbach Publications(Publisher)
The factory method design pattern is a class creational pattern used to encapsulate and defer object instantiation to derived classes. Structurally, the factory method can be modeled as a simplified version of the abstract factory design pattern, since both patterns require creator and product interfaces. However, unlike the abstract factory design pattern, in which the creator objects (i.e., factories) are responsible for instantiating a plurality of products that belong to a specific family type, creator objects in the factory method design pattern are responsible for the creation of a single product of specific type. Therefore, the creator interface for the factory method design pattern provides only one creational method, whereas the creator interface for the abstract factory design pattern provides two or more creational methods. In addition, unlike the abstract factory design pattern, the factory method design pattern defers object creation to subtypes that realize the creational interface; a relationship specified by inheritance, therefore, the factory method design pattern is classified as a class creational design pattern as opposed to an object creational design pattern. These fundamental differences are essential for understanding the difference between both patterns. According to the Gang of Four (Gamma et al. 1995, p. 107), the intent of the factory method is toDefine an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.The factory method design pattern provides the ability for designers to model and implement code in terms of the factory method and product interfaces. The factory method design pattern is mainly characterized by one creational method, which is used to instantiate and return objects of a specified product interface. This creational method is made abstract at the factory base class so that objects of the factory base class cannot be directly instantiated. This is done to create a framework that allows the factory base class to define a series of operations that rely on the product interface; however, before executing operations, object creation is delegated to derived classes that are required to implement the factory (creational) method. This way, new derived factories can override the method to instantiate and return the appropriate product for the particular situation that is then used to carry out the operations specified in the factory base class. This way, through inheritance, new factories can be added to the design of the system to extend the factory base class without modifying its code. With the factory method in place, reasoning about application logic can be made in terms of the product interface and not on concrete products, therefore resulting in code that can be extended easily.Problem
The computer store from the previous example has expanded its operations to have three different stores at different locations. Because of demographics at each location, particular types of computers are offered at specific locations. The computer store in Location 1 supports standard computers only, the computer store at Location 2 supports advanced computers, and the computer store at Location 3 supports a new type of special computer. The software system is now required to display information about computers carried at specific stores. Therefore, the software design requires modification so that the display of computer information is site-specific. A desired feature for the redesigned software is the ability to keep the logic code separate from specific types of computer stores so that future stores, carrying different computers, can be added to the system with minimal effort. - eBook - ePub
- Partha Kuchana(Author)
- 2004(Publication Date)
- Auerbach Publications(Publisher)
IV CREATIONAL PATTERNS Creational Patterns:- Deal with one of the most commonly performed tasks in an OO application, the creation of objects.
- Support a uniform, simple, and controlled mechanism to create objects.
- Allow the encapsulation of the details about what classes are instantiated and how these instances are created.
- Encourage the use of interfaces, which reduces coupling.
Chapter Pattern Name Description 10 Factory Method When a client object does not know which class to instantiate, it can make use of the factory method to create an instance of an appropriate class from a class hierarchy or a family of related classes. The factory method may be designed as part of the client itself or in a separate class. The class that contains the factory method or any of its subclasses decides on which class to select and how to instantiate it. 11 Singleton Provides a controlled object creation mechanism to ensure that only one instance of a given class exists. 12 Abstract Factory Allows the creation of an instance of a class from a suite of related classes without having a client object to specify the actual concrete class to be instantiated. 13 Prototype Provides a simpler way of creating an object by cloning it from an existing (prototype) object. 14 Builder Allows the creation of a complex object by providing the information on only its type and content, keeping the details of the object creation transparent to the client. This allows the same construction process to produce different representations of the object. Passage contains an image
10 FACTORY METHOD
This pattern was previously described in GoF95.DESCRIPTION
In general, all subclasses in a class hierarchy inherit the methods implemented by the parent class. A subclass may override the parent class implementation to offer a different type of functionality for the same method. When an application object is aware of the exact functionality it needs, it can directly instantiate the class from the class hierarchy that offers the required functionality. - eBook - PDF
.NET 7 Design Patterns In-Depth
Enhance code efficiency and maintainability with .NET Design Patterns (English Edition)
- Vahid Farahmandian(Author)
- 2023(Publication Date)
- BPB Publications(Publisher)
• Singleton: Tries to have only one object of the class. These five design patterns can be used interchangeably and can be complementary in some situations. For example, the prototype and abstract factory design patterns may be useful in some situations. Or the singleton pattern may be used in the prototype implementation to make the prototype implementation more complete. Usually, the creational design patterns can be used for the following conditions: • When the system needs to be independent of how the objects are made • When a set of objects are to be used together • When there is a need to hide the class implementation from the user's view • When there is a need for different presentations of a complex object. • Sampling should be clear at the time of execution. • When only one object is required to be provided to the user. Apart from the five GoF patterns, other patterns are related to the creation of objects, such as: • Dependency injection pattern: Instead of creating an object, the class receives the required object through the Injector. • Object pooling pattern: It prevents the object from being destroyed and Creational Design Patterns 45 recreated and reuses the existing objects in the recovery method. • Lazy initialization pattern: Delays the creation of the object until it is used. Factory method This section introduces and analyzes the factory method design pattern according to the structure presented in the GoF design patterns section in Chapter 1, Introduction to Design Patterns. Name: Factory method Classification: Creational design patterns Also known as: Virtual constructor Intent: This design pattern tries to delegate the creation of objects to child classes in a parent- child structure. Motivation, Structure, Implementation, and Sample code: Suppose we are building a residential unit and must make a "door". - eBook - ePub
- Theo Despoudis(Author)
- 2021(Publication Date)
- Packt Publishing(Publisher)
Chapter 3: Creational Design Patterns
When developing applications, you design and manage objects all the time. You create them on the fly or when you assign them to variables for later use. If left unnoticed, you can make the code brittle either by having lots and lots of alternative ways to create those objects, or by not managing their lifetime correctly, thus having to deal with memory leaks.The first and most used category of patterns we will explore in detail in this chapter is creational design patterns .You start by learning how the Singleton pattern can help to ensure we merely keep one instance of an object throughout the lifetime of the program. By using the Prototype pattern, you can copy existing objects without going back through the process of creating them from scratch.Using the Builder pattern, you will learn how to break apart the construction flow of complex objects by using a different and more readable representation.Next, you continue comprehending how the Factory method pattern assists us, detecting the proper time to instantiate objects of a specific type at runtime. By learning how to use the Abstract Factory pattern, you can use interfaces that model the creation of dependent objects and leave the implementation details for the concrete factories at runtime.In this chapter, we are going to address the following key topics:- Creational design patterns
- Singleton pattern
- Prototype pattern
- Builder pattern
- Factory Pattern
- Abstract Factory Pattern
By the end of this chapter, you will have a deep understanding of each of the main creational patterns and will be able to use them practically in your applications. You will also gain the necessary insights into using those patterns only when deemed necessary, avoiding any premature improvements and unfit solutions. - No longer available |Learn more
- Pethuru Raj Chelliah, Harihara Subramanian, Anupama Murali, Dr. Kayarvizhy N(Authors)
- 2017(Publication Date)
- Packt Publishing(Publisher)
This pattern suggests to let the subclasses instantiate the needed classes. The factory method defines an interface, but the instantiation is done by subclasses: The preceding structure depicts a factory method, and an application uses a factory to create subtypes with an interface. The benefits of using this are as listed:- Loose coupling : Separates application from the classes and subclasses
- Customization hooks : The factory method gives subclasses a hook for providing an extended version of an object
The impact of using this is that it creates parallel class hierarchies (mirroring each other's structures), so we need to structure in the best possible ways using intelligent children pattern or Defer identification of state variables pattern.Passage contains an image
Abstract factory (kit)
Abstract Factory Pattern is intended to provide an interface if we want to create families of related or dependent objects, but without explicitly specifying their concrete classes:The preceding class diagram depicts the AbstractFactory class structure and a real-time implementation of an abstract Factory Pattern for an application that combines a different set of (heterogeneous) products from two different groups (<<Bank>> and <<Loan>> ).The benefits of this are the following:- Isolating concrete classes
- Making exchanging product families easy
- Promoting consistency among products
Passage contains an image
Builder
The builder is intended to separate the construction of a complex object from its representation so that the same construction process can create different representations. In other words, use this pattern to simplify the construction of complex object with simple objects in a step-by-step manner:The class diagram depicts a typical builder pattern structure and a sample implementation classes for the Builder pattern. The Builder (TextConverter ) is an abstract Interface that creates parts of a product page. The Concrete Builder (AsciiConv , TexConv ) constructs and assembles parts by interface implementation, the Director (Reader ) constructs an object with the builder interface, and the Products (AsciiTxt , Text - eBook - PDF
- MATT ZANDSTRA(Author)
- 2016(Publication Date)
- Apress(Publisher)
On the other hand, I can build more flexible creators. The base creator class can provide a make() method that guarantees a default implementation of each product family. Concrete children could then modify this behavior selectively. It would be up to implementing creator classes to call the default make() method after providing their own implementation. You will see another variation on the Abstract Factory Pattern in the next section. CHAPTER 9 ■ GENERATING OBJECTS 199 Prototype The emergence of parallel inheritance hierarchies can be a problem with the Factory Method pattern. This is a kind of coupling that makes some programmers uncomfortable. Every time you add a product family, you are forced to create an associated concrete creator (the BloggsCal encoders are matched by BloggsCommsManager , for example). In a system that grows fast enough to encompass many products, maintaining this kind of relationship can quickly become tiresome. One way of avoiding this dependency is to use PHP’s clone keyword to duplicate existing concrete products. The concrete product classes themselves then become the basis of their own generation. This is the Prototype pattern. It enables you to replace inheritance with composition. This in turn promotes runtime flexibility and reduces the number of classes you must create. The Problem Imagine a Civilization-style web game in which units operate on a grid of tiles. Each tile can represent sea, plains, or forests. The terrain type constrains the movement and combat abilities of units occupying the tile. You might have a TerrainFactory object that serves up Sea , Forest , and Plains objects. You decide that you will allow the user to choose among radically different environments, so the Sea object is an abstract superclass implemented by MarsSea and EarthSea. Forest and Plains objects are similarly implemented. The forces here lend themselves to the Abstract Factory Pattern. - eBook - PDF
- Stephen H. Kaisler(Author)
- 2005(Publication Date)
- Wiley-Interscience(Publisher)
Creational patterns focused on creating objects—whether through sub- classes or other objects. Structural patterns use inheritance to compose classes or specify ways to assemble objects. Behavioral patterns use inheritance to describe algorithms and flow of control or to describe how a group of objects can cooperate to perform a task that no single object can carry out alone. Since the early 1990s, numerous disciplines have been subjected to the process of identifying and describing patterns, including analysis patterns (Fowler 1997), orga- nizational patterns (Coplien 1997), and configuration management (Hunt and Tichy 1994). PATTERN SPACES 43 Table 3-1. The Gang of Four pattern space Purpose Design Patterns Aspect(s) that Can Vary Creational Abstract Factory Families of product objects Builder How a composite object gets created Factory Method Subclass of object that is instantiated Prototype Class of object that is instantiated Singleton Sole instance of a class Structural Adapter Interface to an object Bridge Implementation of an object Composite Structure and composition of an object Decorator Responsibilities of an object without subclassing Facade Interface to a subsystem Flyweight Storage costs of objects Proxy How an object is accessed; its location Behavioral Chain of Responsibility Object that can fulfill a request Command When and how a request is fulfilled Interpreter Grammar and interpretation of a language Iterator How an aggregate’s elements are accessed, traversed Mediator How and which objects interact with each other Memento What private information is stored outside an object, and when Observer Number of objects that depend on another object; how the dependent objects stay up to date State States of an object Strategy An algorithm Template Method Steps of algorithm Visitor Operations that can be applied to object(s) without changing their class(es) 3.4 TYPES OF SOFTWARE PATTERNS Patterns can also be classified based on their level of abstraction.
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.









