一种采用多种类型的方法 [英] A method to take a number of types

查看:148
本文介绍了一种采用多种类型的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用一个构造函数接受类型对象
我然后测试它的类型基于instanceof

I currently am working with a constructor which takes in of type object I am then testing it's type based on instanceof

Public MyClass (Object obj)
{
if(obj instanceof CusClass1){
CusClass1 myObject = (CusClass1) obj;
globalVar1 = myObject.getAttrib1();
globaVar2 = myObject.getAttrib2();
}
if(obj instanceof CusClass2){
CusClass2 myObject = (CusClass2) obj;
globalVar1 = myObject.getAttrib1();
globaVar2 = myObject.getAttrib2();
}
}

这可以被偏移到initalise方法构造函数。主要的问题是在对象的铸造。我总是觉得重复的代码是坏的代码。

Can this be offset to an initalise method called from within the constructor. The major problem is in the casting of the Object. I was always under the impression that repeated code is bad code. Can this be made more elegant?

推荐答案

一个更好,更安全的设计是创建多个重载的构造函数。然后你不需要任何转换,并且你不可能通过传递一个不适当类型的对象来构造一个对象。

A much better, more type-safe design would be to create multiple overloaded constructors. You would then not need any casts, and you would make it impossible to construct an object by passing it an object of an inappropriate type.

public MyClass(CusClass1 myObject) {
    globalVar1 = myObject.getAttrib1();
    globalVar2 = myObject.getAttrib2();
}

public MyClass(CusClass2 myObject) {
    globalVar1 = myObject.getAttrib1();
    globalVar2 = myObject.getAttrib2();
}

Do CusClass1 CusClass2 具有相同的 getAttrib1() getAttrib2()方法?然后考虑创建这两个类都实现的接口,并创建一个构造函数,它接受一个实现该接口的对象:

Do CusClass1 and CusClass2 have the same getAttrib1() and getAttrib2() methods? Then consider creating an interface that both these classes implement, and create a constructor that takes an object that implements that interface:

public interface Attribs {
    String getAttrib1();
    int getAttrib2();
}

public class CusClass1 implements Attribs {
    // ...
}

public class CusClass2 implements Attribs {
    // ...
}

public class MyClass {
    // You can now pass anything that implements interface Attribs
    public MyClass(Attribs myObject) {
        globalVar1 = myObject.getAttrib1();
        globalVar2 = myObject.getAttrib2();
    }
}

这篇关于一种采用多种类型的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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