简体   繁体   English

OO-使用无参数的方法创建对象

[英]OO - Creating object using a method of no argument

I am experience some problems in understanding how the OO pattern works, My lecturer gave me the following question but I cannot solve it after thinking whole day 我在理解OO模式的工作方式时遇到了一些问题,我的讲师给了我以下问题,但我一整天都无法解决

Scenario for my problems. 我的问题的方案。

There is a class named "ShapeManager" which manages the Shape object. 有一个名为“ ShapeManager”的类,用于管理Shape对象。 A class named "Shape" has two subclasses named " Circle " and " Rectangle " 名为“ Shape”的类具有两个名为“ Circle ”和“ Rectangle ”的子类。

The implementation of Shape class as follow Shape类的实现如下

abstract public class Shape {
    private String id;
    private double length;

    public Shape() {

    }
    public Shape(String id , double length) {
        this.id = id;
        this.length = length;
    }
    public void setID(String id) {
        this.id = id;
    }
    public String getID() {
        return id;
    }
    public void setLength(double length) {
        this.length = length;
    }
    public double getLength() {
        return length;
    }
    public abstract String getDetails();

}

The subclass Square as follow Square的子类如下

public class Square extends Shape{

    public Square() {
        super();
   }
    public Square(String id , double side) {
        super(id, side);
    }

    @Override
    public String getDetails() {
        return "Square => Id : "+getID() +", Side : "+ getLength() + ",Area : "+(getLength() * getLength());
    }
}

The subclass Circle as follow 子类Circle如下

public class Circle extends Shape{
    public Circle(){
        super();
    }
    public Circle (String id, double radius) {
        super(id, radius);

    }

    @Override
    public String details() {        
        return "Circle => Id : "+getID() + ", Radius : "+ getLength() + ",Area: "+(3.14*(getLength() * getLength()));
    }
}

The ShapeManager class as follow, this is not a completed class ShapeManager类如下,这不是一个完整的类

public class ShapeManager {
    public Shape createShape() {

    }
    public void updateLength(String id ){

    }
    public void deleteShape(String id) {

    }
    public void listShapes() {

    }

}

ShapeManager have an association with Shape ShapeManagerShape有关联

ShapeManager --1------0..*--> Shape

The design of this package (All the classes above) can not be changed, implementation must be following OCP (Open-Closed Principle). 此软件包(以上所有类)的设计不能更改,实现必须遵循OCP(开放-封闭原则)。

My question is: How am I suppose to complete createShape method? 我的问题是:我应该如何完成createShape方法? Without parameter, it is seemingly impossible to create an object either a Rectangle or Circle. 没有参数,似乎不可能创建矩形或圆形的对象。

ShapeManager cannot create a shape if not knowing what this shape is (Square, Circle or something else). 如果不知道形状是什么(正方形,圆形或其他形状),则ShapeManager无法创建形状。 And it really doesn't know because you say the method createShare has no parameters. 而且它真的不知道,因为您说方法createShare没有参数。 Either you misunderstood the question or the lecturer didn't explain it well. 您可能误解了这个问题,或者讲师没有很好地解释它。 You should ask him/her for clarifications. 您应该要求他/她澄清。 If you look at the libraries of Java or any other OO language, I am pretty sure you won't find such scenario and implementation pattern as the one you gave in your example. 如果您查看Java或任何其他OO语言的库,我很确定您不会找到如您在示例中给出的那样的方案和实现模式。


@croraf @croraf

You should find some other reading I think eg the classic book http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612 . 我认为您应该找到其他阅读内容,例如经典书籍http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612 The main idea of a factory is that it returns something whose type the caller doesn't know, and doesn't care about. 工厂的主要思想是,它返回调用者不知道且不关心的类型。 For example, if you have a method createSocket() in some SocketFactory, this method is usually defined to return an interface or an abstract class Socket. 例如,如果您在某些SocketFactory中有一个createSocket()方法,则通常将该方法定义为返回接口或抽象类Socket。 But actually it returns new SocketImpl1() and new SocketImpl2() which are concrete classes. 但是实际上它返回了具体类的新SocketImpl1()和新SocketImpl2() What the factory returns may depend on many things - a system property, the underlying OS, anything you can think of. 工厂返回的内容可能取决于许多因素-系统属性,底层操作系统以及您能想到的任何东西。 The main idea is that the factory centralizes the creation of Socket objects at one single place. 主要思想是工厂将Socket对象的创建集中在一个地方。 This way, if you need to make a change, you can make it just in the factory. 这样,如果您需要进行更改,则可以在工厂中进行更改。 I think this book also has some decent Java counterparts too, you may look around. 我认为这本书也有一些不错的Java同行,您可以看看。 Other free good sources are referenced here. 其他免费的好货源在这里引用。

Real world examples of Factory Method pattern 工厂方法模式的真实示例

I think you should have something like this, similar to how BorderFactory from java API works. 我认为您应该有类似的东西,类似于Java API的BorderFactory的工作方式。

public class ShapeManager {
    public Shape createCircle() {
            ...
            return Circle;
    }
     public Shape createSquare() {
            ....
            return Square;
    }
      ...

   public void updateLength(String id ){

}
public void deleteShape(String id) {

}
public void listShapes() {

}

}

You can't create shape without knowing type which shape would You like to create. 如果不知道要创建哪种形状,就无法创建形状。 You can define enumeration for types and pass the type value to the createShape() . 您可以定义类型的枚举,并将类型值传递给createShape() And there You can switch between types and create the concrette shape You want. 在这里,您可以在类型之间切换并创建所需的饼形。

For me, Its classic Factory pattern . 对我来说,它是经典的Factory pattern

public class ShapeFactory {
  public abstract Shape getShape(int shapeId);
}

 public interface Const {
  public static final int SHAPE_CIRCLE =1;
  public static final int SHAPE_SQUARE =2; 
}


public class SimpleShapeFactory extends ShapeFactory throws BadShapeException {
   public Shape getShape(int shapeTypeId){
    Shape shape = null;
    if(shapeTypeId == Const.SHAPE_CIRCLE) {

    //in future can reuse or cache objects.
      shape = new Circle();
    }
    else if(shapeTypeId == Const.SHAPE_SQUARE) {
      //in future can reuse or cache objects
      shape = new Square();
     }
    else throw new BadShapeException("ShapeTypeId="+ shapeTypeId);
    return shape;
  }
}

Calling: 呼叫:

ShapeFactory factory = new SimpleShapeFactory();

//returns a Shape but whether it is a Circle or a
//Square is not known to the caller.
Shape s = factory.getShape(1);
s.getDetails(); // circle details called
//returns a Shape but whether it is a Circle or a
//Square is not known to the caller.
s = factory.getShape(2);
s.getDetails(); //Square details called

References : 参考文献

The Open Close Principle states that the design and writing of the code should be done in a way that new functionality should be added with minimum changes in the existing code. 开放关闭原则指出,代码的设计和编写应以添加新功能的方式完成,而对现有代码的更改最少 The design should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged. 设计应以允许将新功能作为新类添加的方式进行,并尽可能使现有代码保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM