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 !
  • 相关阅读:
    远离热闹
    漫步泰晤士小镇
    逛2011上海宠物大会(多图)
    iphone 4入手一周使用心得与感受
    章鱼帝
    南非世界杯赛程表下载(Excel版)
    相亲记
    再评富士康悲剧
    上海的朋友出门注意
    有感于车船税
  • 原文地址:https://www.cnblogs.com/maxiaohei/p/14671660.html
Copyright © 2011-2022 走看看