• 工厂方法模式


    一、相关介绍

    1、工厂方法模式定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂方法使一个类的实例化延迟到其子类。

    2、UML图

    3、所属类别:创建型

    二、C++代码

    // 工厂方法模式.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include<iostream>
    using namespace std;
    //抽象产品
    class fruit
    {
    public:
    	fruit();
    	virtual ~fruit();
    	//由于此类是抽象类,没有价格,所以只能将价格显示定义为纯虚函数
    	virtual void show_price()=0;
    };
    fruit::fruit()
    {}
    fruit::~fruit()
    {}
    
    //具体产品1
    class apple :public fruit
    {
    public :
    	apple();
    	virtual ~apple();
    	virtual void show_price();
    };
    apple::apple()
    {
    	cout<<"i am an apple"<<endl;
    }
    apple::~apple()
    {}
    void apple::show_price()
    {
    	cout<<"my price is 5"<<endl;
    }
    
    //具体产品2
    class orange :public fruit
    {
    public :
    	orange();
    	virtual ~orange();
    	virtual void show_price();
    };
    orange::orange()
    {
    	cout<<"i am an orange"<<endl;
    }
    orange::~orange()
    {}
    void orange::show_price()
    {
    	cout<<"my price is 6"<<endl;
    }
    //工厂抽象类
    //输入要创建实例的编号,创建对应实例,1:apple,2:orange
    class fruit_factory
    {
    public:
    	fruit_factory(){}
    	~fruit_factory(){}
    	virtual fruit *creat_fruit()=0;
    };
    //apple工厂类
    class apple_factory:public fruit_factory
    {
    public:
    	apple_factory(){}
    	~apple_factory(){}
    	virtual fruit * creat_fruit()
    	{
    	    return new apple;
    	}
    };
    
    //orange工厂类
    class orange_factory:public fruit_factory
    {
    public:
    	orange_factory(){}
    	~orange_factory(){}
    	virtual fruit * creat_fruit()
    	{
    	    return new orange;
    	}
    };
    int _tmain(int argc, _TCHAR* argv[])
    {
    	orange_factory chengzi_f;
    	fruit *chengzi;
    	chengzi=chengzi_f.creat_fruit();
    	(*chengzi).show_price();
    	return 0;
    }
    

      

  • 相关阅读:
    node中express的中间件之basicAuth
    python练习1--用户登入
    python基础4--文件操作
    python基础3--字符串
    python基础2--字典
    python基础1--列表
    XP下使用IIS访问asp出现无权查看网页问题的解决办法
    jQueryUI Datepicker的使用
    FileUpload控件使用初步
    HTML中表格元素TABLE,TR,TD及属性的语法
  • 原文地址:https://www.cnblogs.com/bewolf/p/4227968.html
Copyright © 2020-2023  润新知