Avoiding parallel inheritance hierarchies

前端 未结 6 917
失恋的感觉
失恋的感觉 2020-12-01 04:46

I have two parallel inheritance chains:

Vehicle <- Car
        <- Truck <- etc.

VehicleXMLFormatter <- CarXMLFormatter
                    <-         


        
6条回答
  •  悲&欢浪女
    2020-12-01 05:01

    You can use Bridge_pattern

    Bridge pattern decouple an abstraction from its implementation so that the two can vary independently.

    Two orthogonal class hierarchies (The Abstraction hierarchy and Implementation hierarchy) are linked using composition (and not inheritance).This composition helps both hierarchies to vary independently.

    Implementation never refers Abstraction. Abstraction contains Implementation interface as a member (through composition).

    Coming back to your example:

    Vehicle is Abstraction

    Car and Truck are RefinedAbstraction

    Formatter is Implementor

    XMLFormatter, POJOFormatter are ConcreteImplementor

    Pseudo code:

     Formatter formatter  = new XMLFormatter();
     Vehicle vehicle = new Car(formatter);
     vehicle.applyFormat();
    
     formatter  = new XMLFormatter();
     vehicle = new Truck(formatter);
     vehicle.applyFormat();
    
     formatter  = new POJOFormatter();
     vehicle = new Truck(formatter);
     vehicle.applyFormat();
    

    related post:

    When do you use the Bridge Pattern? How is it different from Adapter pattern?

提交回复
热议问题