设计模式-工厂模式

一.工厂模式结构示例

工厂模式示例

定义一个创建产品的接口(顶层工厂类),而由该接口的子类(具体工厂类),决定具体实例化哪种产品。即将产品的实例化延迟到接口的子类(具体工厂类)中。也称多态性工厂方法模式或虚拟构造子模式

二.代码示例

public class Main {
    public static void main(String[] args){
        Client client = new Client();
        client.CreateAndUse(new FactoryCat());
    }

}
class Client{
    public void CreateAndUse(Factory factory){
        IAnimal iAnimal = factory.CreateAnimal();
        iAnimal.Sale();
    }
}
abstract class Factory{
    abstract IAnimal CreateAnimal();
}//工厂基类

class FactoryDog extends Factory{
    IAnimal CreateAnimal(){
        return new Dog();
    }
}
class FactoryCat extends Factory{
    IAnimal CreateAnimal(){
        return new Cat();
    }
}

class FactoryFish extends Factory{
    IAnimal CreateAnimal(){
        return new Fish();
    }
}

interface IAnimal{
    void Sale();
}
class Dog implements IAnimal{
    public void Sale(){
        System.out.println("sale dog");
    }
}
class Cat implements IAnimal{
    public void Sale(){
        System.out.println("sale cat");
    }
}
class Fish implements IAnimal{
    public void Sale(){
        System.out.println("sale fish");
    }
}

三.简单工厂模式

简单工厂模式也称为静态工厂模式,且有时工程类可以简单移入产品类中。如下为单产品重载构造函数下应用简单工厂方法示例

class Product{
public:
    static Product CreateNormalProduct(int num);
    static Product CreateFloatProduct(int num,float );
    static Product CreateSpecialProduct(Some& one);
protected:
    Product(int num);
    Product(int num,float a);
    Product(Some& para);
};

Related post

  1. Java 编码

    2020-07-31

  2. 基于RNN的自动文本生成

    2020-07-22

  3. Setting Up and Maintaining a Ubuntu Environment for My Home Server

    2023-11-24

  4. Leetcode Java常用代码

    2024-02-17

There are no comment yet.

COMMENT

Take a Coffee Break

Recommend post

  1. 常用工具指令

    2022-09-18

Category list

ABOUT

Welcome to FullStar, a captivating online destination where the realms of software development and personal reflections intertwine.

April 2025
M T W T F S S
 123456
78910111213
14151617181920
21222324252627
282930  

Life Logs

  1. 回首

    2023-07-14

Return Top