⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 factory method1.txt

📁 C++课件,很好用的,帮助大家学习C++.
💻 TXT
字号:
// ss.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Shape {
	// 勾画shape
public:
	virtual void draw();
	// 擦去 shape
    virtual void erase();
	
	string name;
	Shape(string aName){
		name = aName;
	}
};
// 圆形子类
class Circle :public Shape {
public:
	void draw() {
		cout<<"It will draw a circle."<<endl;
	}
    void erase() {
		cout<<"It will erase a circle."<<endl; 
	}
	// 构造函数
    Circle(string aName):Shape(aName){}
};

// 方形子类
class Square :public Shape {
public:
	void draw() { 
		cout<<"It will draw a square."<<endl; 
	}
    void erase() { 
		cout<<"It will erase a square."<<endl; 
	}
	// 构造函数
    Square(string aName):Shape(aName){}
};
//定义抽象的创建器,anOperation调用factoryMethod创建一个对象,
//并对该对象进行一系列操作.
class ShapeFactory {  
protected:
	virtual Shape factoryMethod(string aName) ;
  // 在anOperation中定义Shape的一系列行为
public:
	void anOperation(string aName){
                 Shape s = factoryMethod(aName);
  	cout<<"The current shape is: " + s.name<<endl;
                s.draw();
	s.erase();
                }
};
//定义与circle和square相对应的两个具体创建器//CircleFactory,SquareFactory,
//实现父类的methodFactory方法
// 定义返回 circle 实例的 CircleFactory
class CircleFactory :public ShapeFactory {
  // 重载factoryMethod方法,返回Circle对象
protected:
	Shape factoryMethod(string aName) {
    return new Circle(aName + "created by CircleFactory");
  }
};
  
// 定义返回 Square 实例的 SquareFactory
class SquareFactory :public ShapeFactory {
  // 重载factoryMethod方法,返回Square对象
protected:
	Shape factoryMethod(string aName) {
    return new Square(aName + " (created by SquareFactory)");
  }
};

int main(int argc, char* argv[])
{
    ShapeFactory *sf1 = new SquareFactory(); 
    ShapeFactory *sf2 = new CircleFactory();
    sf1->anOperation("Shape one");
    sf2->anOperation("Shape two");
    return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -