哪種方法最適合建築設計?這兩者之間的折衷是什麼?還有其他解決方案嗎? 我需要使用多態性來對待RecordBlockReader和PositionBlockReader。 (從InputBS繼承)建築設計之間的權衡
樣本1 - 型鑄造:
class IDataBlock{
public:
virtual void method1() = 0;
}
class RecordBlock: public IDataBlock{
public:
virtual void method01(){/* code */ };
void method02(){ /* code */ };
}
class PositionBlock: public IDataBlock{
public:
virtual void method01(){/* code */ };
void method03(){ /* code */ };
}
class InputBS{
public:
virtual IDataBlock * getNext() = 0;
}
class PositionBlockReader: public InputBS{
public:
virtual IDataBlock *getNext(){ return new PositionBlock(); }
}
class RecordBlockReader: public InputBS{
public:
virtual IDataBlock *getNext(){ return new RecordBlock(); }
}
//Client Code
InputBS *recordBlockReader = new RecordBlockReader();
RecordBlock *recordblock = static_cast<RecordBlock *>(recordBlockReader->getNext());
recordblock->method02();
InputBS *positionBlockReader = new PositionBlockReader();
PositionBlock *positionBlock= static_cast<PositionBlock *>(positionBlockReader->getNext());
positionBlock->method03();
樣品2 - 使用 「胖」 接口:
class IDataBlock{
public:
virtual void method1() = 0;
virtual void method2() = 0;
virtual void method3() = 0;
}
class RecordBlock: public IDataBlock{
public:
virtual void method01(){/* code */ };
virtual void method02(){ /* code */ };
virtual void method03(){ /*throw exception not_supported_operation*/ };
}
class PositionBlock: public IDataBlock{
public:
virtual void method01(){/* code */ };
virtual void method02(){ /*throw exception not_supported_operation*/ };
virtual void method03(){ /* code */ };
}
class InputBS{
public:
virtual IDataBlock * getNext() = 0;
}
class PositionBlockReader: public InputBS{
public:
virtual IDataBlock *getNext(){ return new PositionBlock(); }
}
class RecordBlockReader: public InputBS{
public:
virtual IDataBlock *getNext(){ return new RecordBlock(); }
}
//Client Code
InputBS *recordBlockReader = new RecordBlockReader();
IDatablock *recordblock = recordBlockReader->getNext();
recordblock->method02();
InputBS *positionBlockReader = new PositionBlockReader();
IDatablock *positionBlock= positionBlockReader->getNext();
positionBlock->method03();
我知道java集合實現了第二個選項,拋出異常不支持的操作... –
你會如何使用這個例子中的組合? –