Design Model (II)-factory Model

Source: Internet
Author: User

Factory)
Four roles are involved: Abstract Factory roles, specific factory roles, abstract product roles, and specific product roles.
Abstract Factory roles use interfaces or parent classes to describe factory behaviors,
A specific factory role is responsible for creating a certain type of product objects.
Abstract product classes can use interfaces or parent classes to describe the behavior characteristics of product objects.
A specific product class is a specific object.

The factory mode is different from the static factory mode:
The factory model also achieves polymorphism in the factory class, not just on the product object.
It can correspond to a specific factory for different types of products.

The design mode is as follows:

Abstract Factory ifacloud

package org.test.design.f;/** *  * @author lushuaiyin * */public interface IFactory {IProduct createProduct();}

Specific factory class carfactory computerfactory

package org.test.design.f;public class CarFactory implements IFactory {public IProduct createProduct() {return new Car();}}

package org.test.design.f;public class ComputerFactory implements IFactory {public IProduct createProduct() {return new Computer();}}

Abstract product class iproduct

package org.test.design.f;public interface IProduct {void work();}

Product-specific car computer

package org.test.design.f;public class Car implements IProduct{public void work() {System.out.println("I am car.");}}

package org.test.design.f;public class Computer implements IProduct{public void work() {System.out.println("I am Computer.");}}

Test:

Package Org. test. design. f; public class testmain {/*** @ Param ARGs */public static void main (string [] ARGs) {ifactory carfactory = new carfactory (); iproduct car = (iproduct) carfactory. createproduct (); car. work (); ifactory pcfactory = new computerfactory (); iproduct Pc = (iproduct) pcfactory. createproduct (); PC. work () ;}/ * print I am car. I am computer. */

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.