zoukankan      html  css  js  c++  java
  • python设计模式 之 简单工厂模式

    简单工厂模式属于类的创建型模式,适合用来对大量具有共同接口的类进行实例化,它能够推迟到执行的时候才动态决定要创建哪个类的实例。而不是在编译时就必须知道要实例化哪个类。

    python:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    class Circle(object):
    	def draw(self):
    		print 'draw circle'
    
    class Rectangle(object):
    	def draw(self):
    		print 'draw Rectangle'
    
    class ShapeFactory(object):
    	def create(self, shape):
    		if shape == 'Circle':
    			return Circle()
    		elif shape == 'Rectangle':
    			return Rectangle()
    		else:
    			return None
    
    fac = ShapeFactory()
    obj = fac.create('Circle')
    obj.draw()


    c++:

    #include <iostream>
    #include <string.h>
    using namespace std;
    
    class Shape
    {
    public:
    	virtual void draw(){}
    };
    
    class Circle : public Shape
    {
    public:
    	void draw()
    	{
    		cout << "draw circle" << endl;
    	}
    };
    
    class Rectangle : public Shape
    {
    public:
    	void draw()
    	{
    		cout << "draw Rectangle" << endl;
    	}
    };
    
    class ShapeFactory
    {
    public:
    	static Shape* create(const char *opt)
    	{
    		if (opt == NULL)
    			return NULL;
    
    		if (!strcmp(opt, "Circle"))
    			return new Circle();
    		else if (!strcmp(opt, "Rectangle"))
    			return new Rectangle();
    		else 
    			return NULL;
    	}
    };
    
    int main()
    {
    	Shape *obj = ShapeFactory::create("Rectangle");
    	
    	if (obj)
    		obj->draw();
    	
    	return 0;
    }
    


     

     

  • 相关阅读:
    python2代码改成python3踩过的坑
    Mac下为什么有的文件名后带一个* 星号?
    Mac 的 Vim 中 delete 键失效的原因和解决方案(转)
    使用pandas处理大型CSV文件(转)
    Java基础——02
    javaee相关基础
    Cookie&Session笔记
    EL&JSTL笔记------jsp
    JavaWeb基础
    Java基础——01
  • 原文地址:https://www.cnblogs.com/lytwajue/p/7049081.html
Copyright © 2011-2022 走看看