我想了解 Java 编程中的对象创建最佳实践。我在下面给出了一个例子请检查并建议我Java中的孤儿对象好还是坏?
我有一个Shape
界面。
Circle implements Shape
Square implements Shape
Cube implements Shape
Sphere implements Shape
方法#1 导致孤立对象,方法#2 导致不必要的引用。哪种方法是最佳实践?
方法#1
Shape shape;
shape = new Circle(); // CREATES CIRCLE OBJECT
shape.draw();
shape = new Cube(); // CREATES CUBE OBJECT
shape.draw();
shape = new Sphere(); // CREATES SPHERE OBJECT
shape.draw();
shape = new Square(); // CREATES SQUARE OBJECT
shape.draw();
方法#2
Circle circle = new Circle();
circle.draw();
Cube cube = new Cube();
cube.draw();
Sphere sphere = new Sphere();
sphere.draw();
Square square = new Square();
square.draw();