zoukankan      html  css  js  c++  java
  • 创建型模式-工厂方法 (python实现 与 java实现)

    python 实现

    `
    import abc

    抽象类,定义方法,不具体实现方法,继承类具体实现方法

    class Shape(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def draw(self):
    pass

    工厂类

    class Rectangle(Shape):
    """A simple"""

    def draw(self):
        print("Inside Rectangle::draw() method.")
    

    工厂类

    class Square:
    """A simple localizer a la gattext"""

    def draw(self):
        print("Inside Square::draw() method.")
    

    class ShapeFactory:
    def getShape(self, shapeType: str):
    if shapeType == None:
    return
    if shapeType.upper() == "RECTANGLE":
    return Rectangle()
    elif shapeType.lower() == "square":
    return Square()
    return

    if name == 'main':
    # 实例化工厂类
    shapeFactory = ShapeFactory()
    shape1 = shapeFactory.getShape("rectangle")
    shape1.draw()

    shape2 = shapeFactory.getShape("square")
    shape2.draw()
    

    `

    java 实现

    main.java

    `
    public interface Shape {
    void draw();
    }

    public class Rectangle implements Shape{
    @Override
    public void draw() {
    System.out.println("Inside Rectangle::draw() method.");
    }
    }

    public class ShapeFactory {
    public Shape getShape(String shapeType){
    if (shapeType==null){
    return null;
    }
    if (shapeType.equalsIgnoreCase("square")){
    return new Square();
    }
    else if (shapeType.equalsIgnoreCase("rectangle")){
    return new Rectangle();
    }
    return null;
    }
    }

    public class Main {
    public static void main(String[] args){
    // 创建工厂类实例
    ShapeFactory shapeFactory = new ShapeFactory();
    // 使用工厂类实例 方法获取具体的 细节类
    Shape shape1 = shapeFactory.getShape("Rectangle");
    // 细节类调用
    shape1.draw();

        // 使用工厂类实例 方法获取具体的 细节类
        Shape shape2 = shapeFactory.getShape("square");
        // 细节类调用
        shape2.draw();
    }
    

    }

    `

    LESS IS MORE !
  • 相关阅读:
    入门级: WinForm 下的 ComboBox,ListBox 的使用 (一)
    C#:谨慎 DateTime.Now 带来的危险
    HTML5 小游戏审核通过,请各位有兴趣的朋友帮忙投票!谢谢。
    基于fpga的单线激光雷达数据处理
    左右法则-复杂指针解析
    智能指针(auto_ptr和shared_ptr) 转
    iphone游戏引擎
    C++对象和内存
    让你的代码变的更加强大
    Class Loader
  • 原文地址:https://www.cnblogs.com/maxiaohei/p/14671660.html
Copyright © 2011-2022 走看看