当具体对象采用不同的构造函数参数时,Java中的工厂 [英] Factory in Java when concrete objects take different constructor parameters

查看:323
本文介绍了当具体对象采用不同的构造函数参数时,Java中的工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用Java实现Factory模式。
我有一个名为Shape的类,Circle和Triangle扩展。
问题是Shape构造函数只获得2个参数,而Circle获得3个参数,因此是Triangle(我不会在代码部分显示,因为它与Circle相同)。
为了更好地演示它:

I'm trying to implement a Factory pattern in Java. I have a class called Shape which Circle and Triangle extends. The problem is that Shape constructor gets only 2 parameters while Circle gets 3 parameters and so is Triangle (which I won't show in the code section because is identical to Circle). To demonstrate it better:

    private interface ShapeFactory{
        public Shape create(int x, int y);
    }

    private class CircleFactory implements ShapeFactory{
        public Shape create(float radius, int x, int y){ //error
            return new Circle(radius, x,y);
        }
    }

任何想法如何克服这个问题?我不得在工厂内收到用户的意见(必须从外面收到)。

Any ideas how to overcome this problem? I must not recieve an input from user inside the factory (must be recieved from outside).

谢谢!

推荐答案

您有两种选择:

1)抽象工厂

RectangularShape扩展形状

RoundShape扩展Shape

RectangularShapeFactory RoundShapeFactory

2) Builder (另见有效Java中的第2项)

2) Builder (see also Item 2 in Effective Java)

public Shape {
    private final int x;
    private final int y;
    private final double radius;

    private Shape(Builder builder) {
        x = builder.x;
        y = builder.y;
        radius = builder.radius;
    }

    public static class Builder {
        private final int x;
        private final int y;
        private double radius;

        public Builder(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public Builder radius(double radius) {
            this.radius = radius;
            return this;
        }

        public Shape build() {
            return new Shape(this);
        }    
    }
}

//in client code 

    Shape rectangle = new Shape.Builder(x,y).build();
    Shape circle = new Shape.Builder(x,y).radius(radiusValue).build();

这篇关于当具体对象采用不同的构造函数参数时,Java中的工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆