Difference between the factory pattern and the abstract factory pattern
The factory pattern, also known as the mouse factory, is a parent class that has the interface to produce a mouse. Dell mouse factory, HP mouse factory inherit it, can produce Dell mouse, HP mouse respectively. The production of which mouse is no longer determined by the parameters, but the creation of the mouse factory, created by the Dell mouse factory.
Abstract factory pattern is also not only the production of the mouse, but also the production of the keyboard. That is, the PC manufacturer is a parent class that has two interfaces to produce a mouse and a keyboard. Dell factory, Hewlett-Packard factory to inherit it, you can respectively produce Dell mouse + Dell keyboard, and Hewlett-Packard mouse + Hewlett-Packard keyboard. When a factory is created, it is created by the Dell factory.
When creating an object, the Factory pattern does not use new to create an object, but uses the Factory pattern; the Simple Factory pattern creates an object using the fw pattern; “The Abstract Factory Pattern uses an iterative pattern to create objects.
The Factory pattern allows you to set variables at any time without having to set them in advance. “The Simple Factory Pattern requires the use of defined variables such as parameters or configuration files before the next step can be taken. “The Abstract Factory Pattern requires you to modify the class methods every time you add a product.
Factory method pattern introduces the difference between abstract product and abstract factory?
The Factory method pattern introduces the concepts of abstract and concrete products, where each concrete factory can produce one or more concrete products, and the client can get the desired products through the factory methods. The Abstract Factory pattern introduces the concepts of abstract and concrete factories. Each abstract factory can produce one or more types of products, and the client can obtain the desired products through the abstract factory.
Both patterns can be used to solve object creation problems, but they have some differences in usage. The factory method pattern is used in the case of producing a single product, while the abstract factory pattern is used in the case of producing multiple products. The factory method pattern is more flexible and can be used to add new products and factories as needed, while the abstract factory pattern is more stable and can provide highly encapsulated product groups.
In summary, both patterns are used to solve the object creation problem.
Software Design Patterns which are mainly
Software design patterns are mainly the following three categories of a total of 23 kinds:
One, the creation of patterns:
1, the factory method pattern factory method pattern is created because of the simple factory pattern there is a problem in the simple factory pattern in the creation of the class relies on the factory class, if you want to expand the program, the factory class must be modified! This violates the principle of open and closed, so there is a factory method pattern, only need to create a factory interface and multiple factory implementation classes.
2, Abstract Factory Pattern Abstract Factory Pattern is to provide a series of related or interdependent objects to create a series of interfaces, without having to specify their specific classes. The difference between the factory method pattern, the factory method pattern is to create a factory, you can implement a variety of objects; and the abstract factory pattern is to provide an abstract factory interface, inside the definition of a variety of factories, each factory can produce a variety of objects.
3, single-case pattern single-case pattern ensures that a class has only one instance, and provides a global access point to access it , while creating a single object inside the class, by setting permissions, so that the class can not be created outside the object. A single instance object ensures that only one instance of that object exists in a JVM.
4, builder pattern builder pattern is a complex construction and its representation of the separation, so that the same construction process can create a different representation. In the program is the basic components that will not change, through the builder to the combination, the construction of complex objects to achieve separation.
5, prototype pattern: prototype pattern is to use the prototype instance to specify the type of object created, and by copying these prototypes to create new objects. In fact, it is a copy of the object and return to the caller, the object needs to inherit Cloneable and override the clone method. The idea of the prototype pattern is to take an object as a prototype, make a copy of it, clone it, and produce a new object similar to the original.
Second, structural patterns:
1, adapter mode adapter mode is to make the original interface is incompatible and can not work together with those classes can work together, connecting the two incompatible, independent of the function of the interface, so that they can work together, the adapter plays the role of intermediary.
2, decorator pattern: decorator pattern is to dynamically add some additional duties to an object, to add some new features to an object, the requirements of the decorated object and the decorated object to implement the same interface, the decorated object holds an instance of the decorated object. In addition to dynamic addition, can also be dynamically withdrawn, to do dynamic form, can not be realized with inheritance, because inheritance is static.
3, proxy mode proxy mode is to provide a proxy for other objects to control access to this object, that is, the creation of a class of proxy classes, indirect access to the proxy class, the process of controlling its functions.
4, appearance pattern appearance pattern is a subsystem for a set of interfaces to provide a consistent interface, appearance pattern defines a high-level interface, this interface makes this subsystem easier to use.
5, bridge pattern bridge pattern is to separate the abstract part and the realization of the part, so that they can change independently. Bridging pattern is to separate the thing and its concrete implementation, so that they can each change independently (suddenly associated with the mvc pattern).
6, combination mode: combination mode is the combination of objects into a tree structure to represent the “part of the whole” hierarchical structure, the combination mode makes the user on a single object and a combination of objects to have consistency in the use of objects.
7, hedonic pattern: hedonic pattern is the use of sharing technology to effectively support a large number of fine-grained objects. The main purpose of the hedonic pattern is to realize the sharing of objects, that is, the shared pool, when the system has more objects can reduce the memory overhead, reuse existing objects of the same kind, if no matching object is found, then create a new object, so that you can reduce the creation of the object, reduce the system memory, improve efficiency.
Three, behavioral patterns:
1, strategy pattern:
Strategy pattern is to define a series of algorithms, encapsulate them one by one, and make them interchangeable, and changes in the algorithm will not affect the use of the algorithm of the customer.
2, template method pattern:
The template method pattern is to define the skeleton of an algorithm in an operation, and will be delayed in some of the steps to subclasses. The pattern is to have a main method in an abstract class and then define 1…. .n methods, which can be abstract or actual methods, defining a class, inheriting that abstract class, overriding the abstract methods, and realizing the calls to the subclasses by calling the abstract class.
Template methods allow subclasses to redefine specific steps of an algorithm without changing the structure of the algorithm, encapsulating fixed steps and fixed logic into template methods. Calling a template method accomplishes those specific steps.
3, observer pattern:
Observer pattern is to define a one-to-many dependency relationship between objects, when the state of an object changes, all objects that depend on it are notified and automatically updated.
That is, when the state of the observed changes, notify all observers, this dependency has a bidirectional, in QQ mailbox email subscription and RSS feeds, when users browse some blogs, often see the RSS icon, in short, when the subscription to the article, if there are subsequent updates, it will notify the user in a timely manner. This phenomenon is a typical observer pattern.
4, iterator pattern:
Iterator pattern is to provide a method of sequential access to the elements of an aggregate object, without exposing the internal representation of the object.
In Java, the aggregated class will be traversing the behavior of each element separated, encapsulated into an iterator, so that the iterator to deal with the task of traversal; so that simplify the aggregated class, while not exposing the aggregated class internally, in our frequent use of the JDK in the various classes are also these basic things.
5, Chain of Responsibility Pattern:
Chain of Responsibility pattern is to avoid the request sender and receiver coupled together, so that multiple objects are possible to receive the request, connect these objects into a chain, and pass the request along the chain until an object to deal with it. There are multiple objects, each holding a reference to the next, so that a chain is formed and requests are passed along this chain until an object decides to handle the request.
6. Command Pattern:
The command pattern encapsulates a request into an object so that the issuer can parameterize the client with different requests. Patterns among the existence of the caller, the receiver, the command of the three objects, the realization of the request and the implementation of the separation; the caller selects the command issued, the command specifies the receiver.
7, memo mode:
Memo mode is in the premise of not destroying encapsulation, capture the internal state of an object, and save this state outside the object. Create a memo class, used to store information about the original class; at the same time create a memo repository class, used to store the memo class, the main purpose is to save a certain state of an object in order to restore the object at the appropriate time, that is, to make a backup.
8, state mode:
State mode is to allow an object to change its behavior when its internal state changes. Objects have multiple states and each state has a specific behavior.
9, visitor mode:
Visitor mode is mainly to separate the data structure from data manipulation. Inside the class being accessed to add an external interface to provide reception for visitors, visitors encapsulate some of the messy operation of the structure of the visited, decoupled structure and algorithms, and at the same time has excellent scalability. In layman’s terms, it is a way to separate the data structure and behavior of the object.
10, the intermediary pattern:
The intermediary pattern is an intermediary object to encapsulate a series of object interactions, the intermediary so that the objects do not need to explicitly refer to each other, thus making it loosely coupled, and can be independently change the interaction between them.
11, interpreter mode:
Interpreter mode is given a language, define its grammatical representation, and define an interpreter, this interpreter to use the logo to interpret the sentences in the language, basically, also used in the scope of this, the application of a narrower scope, for example: the interpretation of regular expressions and so on.
Concepts of software design and what they mean:
Software design patterns are summaries of the experience of designing software and descriptions of successful solutions to recurring design problems in software design. In order to document these successful design experiences and facilitate future use, software design patterns usually contain four basic elements: the pattern name, the problem, the solution, and the effect.
The pattern name is actually an aid to memorization, a technical term used in software design that helps designers communicate with each other.
The problem describes the design scenario faced by the designer and is used to tell the designer under what circumstances to use the pattern.
The solution describes the details of the design, usually with a schematic diagram (e.g., a UML class diagram, a sequence diagram, etc., or possibly some schematic diagrams) and textual descriptions of the solution, and, if possible, some code examples for a deeper understanding of the solution.
Effects describe the strengths and weaknesses of the design solution, which are usually oriented towards qualitative attributes of the software, e.g., scalability, reusability, etc.
The importance of software design patterns lies in design reuse. Design patterns make it easier for designers to borrow from or directly use proven, successful design solutions without having to spend time on design reuse. Some design patterns even provide class diagrams and code examples that provide direct support for design documentation and software development.
What is the difference between the factory pattern, the simple factory pattern, and the abstract factory pattern
The benefit of the factory pattern lies in the reduction of the coupling between the factory and the product, and the construction process of the specific product is placed inside the specific factory class. In the future to extend the product is much more convenient, only need to add a factory class, a product class, you can easily add products, without the need to modify the original code. And in the simple factory, if you want to add a product, you need to modify the factory class, add if/else branch, or add a case branch, the factory pattern in line with the software development in the OCP principle (opencloseprinciple), open to the extension of the closure of the modification.
Abstract Factory Pattern: This pattern I always feel very similar to the builder pattern.
The factory method pattern provides a hierarchical pattern for one product, while the abstract factory method provides a hierarchical pattern for multiple products. Note that the multiple concrete products here are coupled with each other, i.e., there is some kind of connection between the products provided by the abstract factory here.
Some people make the following comparison:
Factory method pattern: an abstract product class that can derive multiple concrete product classes.
An abstract factory class that can derive multiple concrete factory classes.
Each concrete factory class can create only one instance of a concrete product class.
Abstract factory pattern: multiple abstract product classes, each of which can derive multiple concrete product classes.
An abstract factory class that can derive multiple concrete factory classes.
Each concrete factory class can create multiple instances of a concrete product class.
Difference: factory method pattern has only one abstract product class while abstract factory pattern has multiple.
The concrete factory class of the factory method pattern can create only one instance of the concrete product class, while the abstract factory pattern can create multiple.
Here’s a graphic analogy:
Whether it’s the Simple Factory pattern, the Factory pattern, or the Abstract Factory pattern, they all essentially extract the unchanging parts and leave the mutable parts as interfaces to maximize reuse. Take an example of a factory that produces a cup (cup): At first, without using the factory pattern, I must know all the characteristics of the cup such as the material and shape of the cup before I can produce the cup, which is our newCup(); this Cup must be concrete. The factory owner found the same shape of the quilt, just different materials, such as a glass (glass), a porcelain (china), but really want two production lines, there is obviously a waste of resources suspected. Now the owner of the production of cups do not let the production line to know what I want to produce is glass or porcelain, but let it in the case of not knowing the specific material to do it first can do, until it is done to the mold, only need to be filled with raw materials to which the glass or porcelain raw materials can be built in the same shape of the specific cup. But unfortunately, java and can not new an abstract Cup, so there is a simple factory pattern. The original is Cupcup=newCup; now is SimpleCupFactory.createCup (StringcupName), according to the name of the cup production Cup, and createCup return is an implementation of the Cup interface or abstract class of the concrete Cup. simple abstract factory pattern has a problem, that is, when I One problem with the simple abstract factory pattern is that when I want to produce an iron cup of the same shape, there is no corresponding process defined in the factory, and I can only change the createCup method, which doesn’t make sense. I just want to produce iron cups, you just need to change the glass raw material to iron at the end of the time is not on the line, why change the entire production line? So there is a factory model. The original production line in the production of molds have to consider is the production of molds for glass cups or iron cups production molds, now it does not have to care.CupFactory.createCup () to create Cup.CupFactory is an interface or abstract class. A concrete subclass that implements it creates a concrete Cup that conforms to the Cup interface. so now the factory owner wants to produce kettles (kettle), with the factory pattern will have to recreate a kettle production line, can you produce kettles at the same time as the cup production line? This is the abstract factory pattern.
Factory Design Patterns
Like the six principles, each design pattern is an idea, rather than a specific form, so be flexible. This brief analysis of the factory design pattern in the actual development of the application. Factory design pattern is divided into three categories: simple factory, factory methods, abstract factory. The factory method is divided into two forms: single factory form and multi-factory form. This time will be combined with three types of data storage, each form of the factory pattern to analyze. These three types are Memory Storage (LRUCache), SharedPreferece, and Disk Disk Storage, which will be produced by the factory as products.
Below we start by defining an interface for the product to access the data, which will serve as the specification for the three types of data storage.
The abstract methods for accessing the three data types String, int, and boolean were defined above and can be extended here. Then we define the implementation classes for each of the three data storage types:
The above MemoryHandler inherits from ISaveHandler and implements the LruCache memory cache.
SharedPreferenceHandler above inherits from ISaveHandler and implements the SharedPreference cache. There is also disk caching is not written, interested in their own extension. Here mainly explains the factory design pattern. The following began to write a simple factory, simple indeed is also very simple, a factory a switch statement:
The above is through the incoming enumeration type to generate the corresponding storage object. Not much to say, look at the use of it:
The enumerated types of this simple factory pattern benefit is clear and concise type less, not so much beating around the bush. The bad thing is that, when the type of data storage (product type) need to be extended, you need to change the factory. Let’s look at the second one: the factory method pattern.
At the beginning, I said that the factory method pattern consists of two forms, a multi-factory form and a single-factory form.
Above we saw a factory with a single method, which is used to generate storage in the form of SharedPreference. If we want to generate other forms of storage, then we have to create another factory accordingly. Other factories are not posted here. In fact, this approach is more straightforward, but the disadvantages are also very straightforward, that is, the factory thief. So here’s a look at the form with fewer factories.
The above is through the type, and then reflection to get the object of the stored type. This pattern is somewhat similar to the simple factory, except that here there is no need to maintain enumerated classes. When you need to extend the data storage method, you just need to add the data storage type, and you don’t need to change the factory. This is the most widely used factory pattern. Here’s another brief look at its use:
The abstract factory pattern is actually a bit similar to the multi-factory pattern of factory methods, which is easy to confuse. The difference between the two is that under the single factory method pattern, a factory can only produce one product, while under the abstract factory pattern, a factory needs to produce a set of products. For example, here I need a factory that can produce both MemoryStorage objects and SharedPreferece objects. Or, a factory can produce both memory storage objects and disk storage objects and so on. In the actual development process, if you use this abstract factory pattern, then generally speaking, a factory can produce these two objects will have a certain correlation between the two objects. For example, the car factory, it can produce both bearings and tires, the two are very close. Here’s a look at the abstract factory pattern:
Above a factory can produce two products, of course, the above example inside the factory’s two products wood have a strong correlation. As I said earlier, when using this abstract factory approach, there is generally a certain correlation between the products of a factory. Like bearings and tires in a car. Comparatively speaking, in the daily development, the factory method pattern may be more widely used.