Design Pattern Learning: Simple Factory

Source: Internet
Author: User

Brief introduction:

From the type of design pattern, the simple factory pattern belongs to the creation pattern, also known as static Factory method (static Factory methods), but not one of the 23 gof design patterns. A simple factory pattern is a factory object that determines which instances of the product class are created.

Class Diagram:

From the UML class diagram, it can be seen that the simple factory model means that the inner part of a class, which needs to be generated, is extracted and transformed into a factory to new objects through the factory.

Let's say we're going to eat an apple, we can get a new apple out of the code, and when we need to eat a banana, we'll come out with a new banana in the code. This way you will not feel trouble, new things have to do their own. So you can give new things to a factory (as the name suggests, the factory is the place to produce things). And a simple factory decides what products to produce by passing in the parameters.

The words are not clear, please see the following code:

Code:

When we first didn't use the simple factory model, maybe we would do it and look at the following code

Class apple{public
         Apple () {
                   System.out.println ("produced an apple");
         }
 
Class banana{Public
         banana () {
                   System.out.println ("Production of a Banana");
         }
 
public class main{public
         static void Main (string[] args) {
                   applea=new apple ();
                   Bananab=new Banana ();
         }

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.