工厂模式下的形状基类
扫描二维码
随时随地手机看文章
一个形状基类.. 一个圆 一个矩形。。。 一个工厂根据参数返回形状子类 老掉牙的类名..英文不好...
——————————————-java——————————————————-
形状基类
package com.shiji.gongchang; public interface XingZhuang { void Run(); }
package com.shiji.gongchang; //圆形类 继承自形状 public class Circle implements XingZhuang { @Override public void Run() { // TODO Auto-generated method stub System.out.println("Im Cirlce!"); } }
package com.shiji.gongchang; //矩形类 继承自形状 public class Rectangle implements XingZhuang { @Override public void Run() { // TODO Auto-generated method stub System.out.println("Rectangle!"); } }
工厂
package com.shiji.gongchang; public class XingZhuangFactory { public XingZhuang CreateXingzhuang(String obj) { if(obj=="矩形") { return new Rectangle(); }else if (obj=="圆") { return new Circle(); } return null; } }
测试 //工厂模式 public class GongChangMoshi { public static void main(String[] args) { XingZhuangFactory xingZhuangFactory = new XingZhuangFactory(); xingZhuangFactory.CreateXingzhuang("矩形").Run(); xingZhuangFactory.CreateXingzhuang("圆").Run(); } //静态方法 加载C++类库 test.dll static { System.loadLibrary("JniTest"); } }
——————————————-C++——————————————————-
形状基类
#pragma once class Xingzhuang { public: virtual void Run()=0; Xingzhuang(); ~Xingzhuang(); };
圆…
#pragma once #include "Xingzhuang.h" class Circle :public Xingzhuang { public: virtual void Run(); Circle(); ~Circle(); }; cpp: #include "stdafx.h" #include "Circle.h" Circle::Circle() { } Circle::~Circle() { } void Circle::Run() { printf("Im Circle~!"); }
方块,…
#pragma once #include "Xingzhuang.h" class Rectangle :public Xingzhuang { public: virtual void Run(); Rectangle(); ~Rectangle(); }; cpp: #include "stdafx.h" #include "Rectangle.h" Rectangle::Rectangle() { } Rectangle::~Rectangle() { } void Rectangle::Run() { printf("Im Rectangle!"); }
工厂 -,-
#pragma once #include "Xingzhuang.h" enum _Xtype { _rectangle=0, _circle=1 }; class Factory { public: Factory(); Xingzhuang* Create(_Xtype t); ~Factory(); }; cpp: #include "stdafx.h" #include "Factory.h" #include "Circle.h" #include "Rectangle.h" Factory::Factory() { } Factory::~Factory() { } Xingzhuang* Factory::Create(_Xtype t) { if (t==_Xtype::_rectangle) { Rectangle* p = new Rectangle(); return p; }else if (t==_Xtype::_circle) { Circle*p = new Circle(); return p; } return NULL; }
demo:
#include "stdafx.h" #include "Factory.h" inline void test(_Xtype t) { Factory* f = new Factory(); if (f) { Xingzhuang* x = NULL; x = f->Create(t); if (x) { x->Run(); delete x; } delete f; } } int main() { test(_Xtype::_circle); test(_Xtype::_rectangle); return 0; }