간단히 말해, 특정 인터페이스를 구현하지 않는 수퍼 클래스로 클래스 인스턴스를 그룹화 할 수 있기를 바랍니다. 그러나 인스턴스 집합에서 해당 인터페이스를 구현하는 인스턴스의 인터페이스에서 메서드를 호출하고 싶습니다.
그것을 설명 할 수있는 몇 가지 예제 코드.
class Building{
String c = "white";
Building(){
}
void printColor(){
println("The building is " + c);
}
void paint( String c ){
this.c = c;
}
void printBuildQuality(){
println("The build quality is average");
}
}
class SturdyFactoryBuilding extends Building implements Factory{
SturdyFactoryBuilding(){
super();
}
void printBuildQuality(){
println("The build quality is sturdy");
}
void printFactoryOutput(){
println("This factory makes stuff");
}
}
class ShakyFactoryBuilding extends Building implements Factory{
ShakyFactoryBuilding(){
super();
}
void printBuildQuality(){
println("The build quality is shaky");
}
void printFactoryOutput(){
println("This factory makes slightly different stuff");
}
}
public interface Factory{
public void printFactoryOutput();
}
Building building = new SturdyFactoryBuilding();
building.printBuildQuality();
building.printColor();
building.paint("bright red");
building.printColor();
building.printFactoryOutput();
수퍼 클래스에 'isFactory'플래그를 사용하여 이것을 달성 할 수있는 방법이 있습니까?
감사.
나는 당신이 트레이드 오프를해야한다고 생각한다 : 당신은 약간의 안티 패턴을 받아들이거나 당신이 Building
"인터페이스"를 열어 어댑터 역할을한다.
class Building implements Factory{
// the other building stuff
@Override
public void printFactoryOutput(){ /* NO OP */ }
}
그런 다음 호출 할 수 있습니다 printFactoryOutput
모두에 Building
이 시점에 아무런 영향까지이없는 S.
당신 때문에 Factory
-implementations는 확장 Building
NOOP-구현을 상속 자동으로합니다. 그러나 재정의하기 때문에 :
class ShakyFactoryBuilding extends Building implements Factory{
ShakyFactoryBuilding(){
super();
}
@Override
public void printBuildQuality(){
println("The build quality is shaky");
}
@Override
public void printFactoryOutput(){
println("This factory makes slightly different stuff");
}
}
... 원하는 결과를 얻었습니다.
단점은 물론 모든 건물에 printFactoryOutput
가시성 이 있다는 것 입니다. 하지만 그것이 제가 말한 트레이드 오프입니다. 이것이 허용되지 않는 경우 디자인을 완전히 재고해야합니다.
Factory 가 아닌 Building이 해당 Method에서 호출되지 않음을 명확히하기 위해 Building 에서 UnsupportedOperationException을 발생시킬 수 있지만 코드의 모든 곳에서 try / catch 블록을 강제 실행합니다. 부울을 반환 할 수도 있습니다. default = false이고 실제로 공장이라면 true를 반환합니다. 가능성이 많습니다.
상속보다 구성 을 사용하도록 디자인을 변경할 수도 있습니다 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다