Design Pattern Learning -- Abstarct Factory, -- abstarctfactory

Source: Internet
Author: User
Tags mysql delete mysql insert

Design Pattern Learning -- Abstarct Factory, -- abstarctfactory
What

Abstarct Factory: provides an interface for creating a series of related or mutually dependent interfaces without specifying their specific classes.

Why

Abstarct Factory is a type of creation design pattern, which is mainly decoupled when an object is created to avoid direct dependency on the object and facilitate replacement and customization. For example, if a function has two different styles and needs to be switched Based on the configuration, or in a program that needs to be applied to multiple database switches, both use Abstact Factory.
Applicable to Abstarct Factory scenarios:
1. When the system display or function needs to be configurable.
2. Create a system module, which must be independent of the system module.
3. When the system needs to be dynamically customized.

How

In the following scenario, when writing a database access layer, you must support switching between two types of databases. For example, you can switch between sqlserver and mysql. This simple example illustrates the implementation of Abstarct Factory.
First, we define our dao interface:

public interface UserDao {    void insert(User user);    void delete(String id);    User find(String id);}

This interface requires three simple methods: insert, delete, and query.
Define the factory interface for creating Dao instances

public interface DaoFactory {    UserDao create();}

Implementation of UserDao used to access sqlserver

public class SqlServerUserDaoImpl implements UserDao {    @Override    public void insert(User user) {        System.out.println("sqlserver insert user");    }    @Override    public void delete(String id) {        System.out.println("sqlserver delete user");    }    @Override    public User find(String id) {        System.out.println("sqlserver find user");        return null;    }}

Implementation of UserDao for accessing mysql

public class MysqlUserDaoImpl implements UserDao {    @Override    public void insert(User user) {        System.out.println("mysql insert user");    }    @Override    public void delete(String id) {        System.out.println("mysql delete user");    }    @Override    public User find(String id) {        System.out.println("mysql find user");        return null;    }}

The factory used to create sqlserver userDao

public class SqlserverDaoFactoryImpl implements DaoFactory {    @Override    public UserDao create() {        return new SqlServerUserDaoImpl();    }}

The factory used to create mysql userDao

public class MysqlDaoFactoryImpl implements DaoFactory {    @Override    public UserDao create() {        return new MysqlUserDaoImpl();    }}

Client call Method

public class App {    public static void main( String[] args ){        DaoFactory daoFactory=new MysqlDaoFactoryImpl();        UserDao userDao=daoFactory.create();        userDao.insert(null);        DaoFactory daoFactory1=new SqlserverDaoFactoryImpl();        UserDao userDao1=daoFactory1.create();        userDao1.delete("");    }}

The class diagram of the above instance is as follows:

Discuss

In the above example, you can also write the database selection in the configuration file, and load different programs according to the configuration during system startup through reflection, this was previously used when c # was used as a system. In java web development, the spring framework is generally used. It provides IOC technology to initialize data sources by configuring beans.
Abstract Factory is also used in spring Source Code. For example, BeanFactory is an example. Of course, its design is much more complicated than the example in this article.

ChangeLog

The examples in this section are not perfect, so they are improved. In ChangeLog, the difference and connection between the two are added to the Discuss chapter of the Factory Method in design mode learning.
The sample code is modified based on the above example. If you understand the code in the sample, the Code modified to the following structure is relatively simple and will not be posted. You can also download it from my GitHub.


Difficulty arrangement of 23 Java Design Patterns

Creation Mode
1. FACTORY
Try to catch up with MM. Both the chicken wings of McDonald's and the chicken wings of KFC are what MM loves. Although the taste is different, whether you take MM to McDonald's or KFC, just say "four chicken wings" to the waiter. McDonald's and KFC are Factory for chicken wings production.

Factory model: the customer class and the factory class are separated. A consumer needs a product at any time and only requests from the factory. Consumers can accept new products without modification. The disadvantage is that the factory class must be modified when the product is modified. For example, how to create and provide data to clients.

Reply
2 Floor 2, BUILDER
MM is most fond of listening to the sentence "I Love You". When I see MM in different places, I want to be able to speak to her in their dialects. I have a multi-language translator, there is a button in each of the above languages. When you see MM, you only need to press the corresponding key to say "I love you" in the corresponding language, foreign MM can also be easily implemented, which is my "I love you" builder. (This must be better than the US military's translation server in Iraq)

Construction mode: separates the internal appearance of a product from the product generation process, so that a building process generates product objects with different internal appearances. The construction mode allows the product's internal appearance to change independently, so that the customer does not have to know the details of the product's internal composition. The construction model enforces a step-by-step construction process.

Third floor 3, FACTORY METHOD
Ask MM to go to McDonald's for a hamburger. Different MM has different tastes. Remember that it is an annoying thing. I usually use the Factory Method mode and take MM to the waiter, say "I want a hamburger". What kind of hamburger do I need? Just let MM talk to the waiter directly.

Factory method mode: the Core factory category is no longer responsible for the creation of all products. Instead, it submits the specific creation work to the subclass to become an abstract factory role, it is only responsible for providing the interface that must be implemented by a specific factory class, without touching the details of which product class should be instantiated.

4/F 4, PROTOTYPE
When chatting with MM via QQ, I must say some affectionate words. I have collected a lot of emotional words. If necessary, I just need to copy them and put them in QQ, this is my prototype. (100 yuan a copy, do you want)

Original Model mode: specify the type of the object to be created by giving a prototype object, and then create more objects of the same type by copying the prototype object. The original model mode allows you to dynamically add or remove product classes. The product class does not need to have any predefined level structure. The original model mode applies to any level structure. The disadvantage is that each class must have a clone method.

5/F, SINGLETON
I have 6 beautiful wives. Their Husbands are me. I am Sigleton, our family's husband. All they need to say is "husband, that's me (I had a dream just now. How can this be a good thing)

Singleton mode: Singleton mode ensures that a class has only one instance, and instantiate the instance and provides the singleton mode to the entire system. The Singleton mode can only be used when there is a real "Single Instance" demand.

6-floor Structural Model
6. ADAPTER
I met Sarah, a beautiful girl from Hong Kong at a friend's party. But I can't speak Cantonese, but she can't speak Mandarin, so I have to turn to my friend kent, as an Adapter between me and Sarah, Sarah and I can talk to each other (I don't know if he will play with me)

Adapter (transformer) mode: converts an interface of a class into another interface that the client expects, so that the two classes that cannot work together due to interface mismatch can work together. The adaptation class can return a suitable instance to the client based on the parameters.

7. BRIDGE
MM in the morning, good morning, MM in the evening, good evening, and MM in new clothes, nice clothes, and new hair styles, say your hair looks pretty. Don't ask me the question of "how to say MM has a new hairstyle in the morning". If I use BRIDGE to combine it myself, don't you... the rest is full>
 
Java 23 design modes

There are three types of design patterns: creation, structure, and behavior.
The creation types include:
I. Singleton, Singleton mode: ensure that a class has only one instance and provide a global access point to it.
2. Abstract Factory: provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes.
3. Factory Method: Define an interface used to create objects, and let the subclass decide which class to instantiate. Factory Method delays the instantiation of a class to the subclass.
4. Builder: separates the construction of a complex object from its representation, so that different representations can be created during the same construction process.
5. Prototype: Use a Prototype instance to specify the type of the object to be created, and copy the Prototype to create a new object.
Behavior types:
6. Iterator: provides a method to access each element of an aggregate object sequentially without exposing the internal representation of the object.
7. Observer: Observer mode: defines one-to-many dependencies between objects. When the status of an object changes, all objects dependent on it will be automatically updated by notification.
8. Template Method: defines the skeleton of an algorithm in an operation, and delays some steps to the subclass, templateMethod allows the subclass to redefine a specific step without changing the structure of an algorithm.
9. Command: encapsulate a request as an object so that you can parameterize the customer with different requests, queue requests and record request logs, and supports unrecoverable operations.
10. State: allows an object to change its behavior when its internal State changes. The object seems to have changed its class.
11. Strategy: Define a series of algorithms, encapsulate them one by one, and enable them to replace each other. This mode allows algorithms to be independent of customers who use them.
12. China of Responsibility, Responsibility chain mode: Enables multiple objects to process requests to avoid coupling between the request sender and receiver.
13. Mediator: uses an intermediary object to encapsulate object interaction of some columns.
14. Visitor, Visitor mode: indicates an operation that acts on each element in an object structure. It allows you to define new operations that act on this element without changing the element classes.
15th, Interpreter, Interpreter mode: a language is defined to define a representation of its grammar and an Interpreter. This Interpreter uses this representation to explain sentences in the language.
16. Memento: capture the internal state of an object without interrupting the object, and save the state outside the object.
There are:
17. Composite: Composite combines objects into a tree structure to represent the relationship between parts of the whole. Composite makes the use of a single object and a Composite object consistent.
18. Facade, appearance mode: provides a consistent interface for a group of interfaces in the subsystem. fa? Ade provides a high-level interface, which makes the subsystem easier to use.
19. Proxy: provides a Proxy for other objects to control access to this object.
20. Adapter: the Adapter mode converts a class of interfaces into another interface that the customer wants. The Adapter mode makes those classes unable to work together due to interface incompatibility.
21. Decrator: the Decorator mode dynamically adds some additional responsibilities to an object. In terms of the added functions, the Decorator mode is more flexible than the subclass generation mode.
22. Bridge: link the abstract Part with its implementation... the remaining full text>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.