Difference between Bridge pattern and Adapter pattern

后端 未结 9 988
清歌不尽
清歌不尽 2020-11-29 19:16

What is the difference between the Bridge and Adapter patterns?

相关标签:
9条回答
  • 2020-11-29 19:42

    There are plenty of answers To distinguish between Adapter and Bridge. But as ppl are looking for code examples, I would give one example for Adapter Design Pattern crafted into a timeline story :

        //---------------------------------------External Vendor/Provider--------------------------------
       
                //Adaptee | RussianTankInterface is adaptee | adaptee lives in is own lala land and do not care about any other class or interface
                RussianTankInterface smerch9K58 = new RussianTank("The Russian Artillery bought by India in October 2015");
                    smerch9K58.aboutMyself();
                    smerch9K58.stuff();
                    smerch9K58.rotate();
                    smerch9K58.launch();
            
       
        //---------------------------------2016 : India manufactures Bharat52 ------------------------------ 
        
                //Client_1 :: IndianTank 
                EnemyAttacker bharat52Attacker = new IndianTank("Tank built in India delivered to Army in Jul 2016"); 
       
                // behaves normally -------------------------(1)
                    bharat52Attacker.aboutMe();
                    bharat52Attacker.load();
                    bharat52Attacker.revolve();
                    bharat52Attacker.fireArtillery();
                    
        //---------------------------------2019 : India mnufactures Pinaka, and thought about fusion with Russian technology - so adaption required ------------------------------ 
                      
                //Client_2 :: IndianTank 
                EnemyAttacker pinakaAttacker = new IndianTank("Tank built in India in 1998 got upgraded_v1 in 9 Sep 2019"); 
                
                
                
    #####----Bilateral-Coalition happens----## 
    #####       India  : I want a fusion artillery technology with 
    #####                       1) Indian materials and brain-power but
    #####                       2) Russian machine-parts-movement technology 
    #####       Russia : Give me your Interface - at max we can help by providing an Adapter 
        
        //---------------------------------------External Vendor/Provider-----------------------------------
        
                //Adapter :: RussianTechnologyAdapter | Russia gets EnemyAttacker interface only from India & creates RussianTechnologyAdapter 
                RussianTechnologyAdapter russianTechnologyAdapter = new RussianTechnologyAdapter(smerch9K58);
               
               
                //Target | EnemyAttacker was initially ClientInterface but later becomes the Target as story evolves | <- client owns this Interface
                EnemyAttacker dhanushAttacker = russianTechnologyAdapter;
                
    #####----Russia keeps her Word----## 
    #####       Russia to India : Here you go! Take Dhanush, a wrapper over our encapsulated adapter, and plug-in anything conforming to your EnemyAttacker.
    #####       India : Thanks a lot!
    
        //--------------------------------- 2020 : India returns back happily with dhanushAttacker--------------------------------------- 
                
                //Client_2 - adapted behavior -------------------------(2)
                    dhanushAttacker.setNavigationCapability(pinakaAttacker.getCuttingEdgeNavigableTargets());
                    dhanushAttacker.aboutMe(); //calls RussianInstance -> aboutMyself()
                    dhanushAttacker.load();    //calls RussianInstance -> stuff()
                    dhanushAttacker.revolve(); //calls RussianInstance -> rotate()
                    dhanushAttacker.fireArtillery();  //calls RussianInstance -> launch()
                           
              
    

    Carefully notice :

    • Same API in (1) & (2) behaves differently
    • India can push its brain into wireFrame of Russia e.g dhanushAttacker.setNavigationCapability(pinakaAttacker.get(..))

    Noteworthy points

    Client side owns:

    -  Invoker /Use(uses Adapter later point)/Client
    -  ClientInterface (a.k.a Target )
    

    Shared later:

    - ClientInterface  ( becomes Target after sharing)
    

    Receiver side owns :

    - Adapter (later shared directly or as a wrapper )  
    - Adaptee
    
         
    

    Hoping someone gives an inline for Bridge too :)

    0 讨论(0)
  • 2020-11-29 19:43

    "Adapter makes things work after they're designed; Bridge makes them work before they are. [GoF, p219]"

    Effectively, the Adapter pattern is useful when you have existing code, be it third party, or in-house, but out of your control, or otherwise not changeable to quite meet the interface you need it to. For instance, we have a SuperWeaponsArray which can control a fine array of doomsday devices.

    public class SuperWeaponsArray {
      /*...*/
    
      public void destroyWorld() {
        for (Weapon w : armedWeapons) {
          w.fire();
        }
      }
    }
    

    Great. Except we realize we have a nuclear device in our arsenal that vastly predates the conversion to the Weapon interface. But we'd really like it to work here... so what do we do... wedge it in!

    NukeWeaponsAdaptor - based off of our Nuke class, but exporting the Weapon interface. Sweet, now we can surely destroy the world. It seems like bit of a kludge, but it makes things work.


    The Bridge pattern is something you implement up front - if you know you have two orthogonal hierarchies, it provides a way to decouple the interface and the implementation in such a way that you don't get an insane number of classes. Let's say you have:

    MemoryMappedFile and DirectReadFile types of file objects. Let's say you want to be able to read files from various sources (Maybe Linux vs. Windows implementations, etc.). Bridge helps you avoid winding up with:

    MemoryMappedWindowsFile MemoryMappedLinuxFile DirectReadWindowsFile DirectReadLinuxFile

    0 讨论(0)
  • 2020-11-29 19:46

    http://en.wikipedia.org/wiki/Adapter_pattern

    The Adapter pattern is more about getting your existing code to work with a newer system or interface.

    If you have a set of company-standard web service APIs that you'd like to offer to another application's existing extensibility interface, you might consider writing a set of adapters to do this. Note that there's a grey area and this is more about how you technically define the pattern, since other patterns like the facade are similar.

    http://en.wikipedia.org/wiki/Bridge_pattern

    The Bridge pattern is going to allow you to possibly have alternative implementations of an algorithm or system.

    Though not a classic Bridge pattern example, imagine if you had a few implementations of a data store: one is efficient in space, the other is efficient in raw performance... and you have a business case for offering both in your app or framework.

    In terms of your question, "where I can use which pattern," the answer is, wherever it makes sense for your project! Perhaps consider offering a clarification edit to guide the discussion on where you believe you need to use one or the other.

    0 讨论(0)
  • 2020-11-29 19:47

    In the top answer, @James quotes a sentence from the GoF, page 219. I think it's worthwhile reproducing the full explanation here.

    Adapter versus Bridge

    The Adapter and Bridge patterns have some common attributes. Both promote flexibility by providing a level of indirection to another object. Both involve forwarding requests to this object from an interface other than its own.

    The key difference between these patterns lies in their intents. Adapter focuses on resolving incompatibilities between two existing interfaces. It doesn't focus on how those interfaces are implemented, nor does it consider how they might evolve independently. It's a way of making two independently designed classes work together without reimplementing one or the other. Bridge, on the other hand, bridges an abstraction and its (potentially numerous) implementations. It provides a stable interface to clients even as it lets you vary the classes that implement it. It also accommodates new implementations as the system evolves.

    As a result of these differences, Adapter and Bridge are often used at different points in the software lifecycle. An adapter often becomes necessary when you discover that two incompatible classes should work together, generally to avoid replicating code. The coupling is unforeseen. In contrast, the user of a bridge understands up-front that an abstraction must have several implementations, and both may evolve independently. The Adapter pattern makes things work after they're designed; Bridge makes them work before they are. That doesn't mean Adapter is somehow inferior to Bridge; each pattern merely addresses a different problem.

    0 讨论(0)
  • 2020-11-29 19:52

    This post has been around for quite a while. However, it is important to understand that a facade is somewhat similar to an adapter but it's not quite the same thing. An adapter "adapts" an existing class to a usually non-compatible client class. Let's say that you have an old workflow system that your application is using as a client. Your company could possibly replace the workflow system with a new "incompatible" one (in terms of interfaces). In most cases, you could use the adapter pattern and write code that actually calls the new workflow engine's interfaces. A bridge is generally used in a different way. If you actually have a system that needs to work with different file systems (i.e. local disk, NFS, etc.) you could use the bridge pattern and create one abstraction layer to work with all your file systems. This would basically be a simple use case for the bridge pattern. The Facade and the adapter do share some properties but facades are usually used to simplify an existing interface/class. In the early days of EJBs there were no local calls for EJBs. Developers always obtained the stub, narrowed it down and called it "pseudo-remotely". This often times caused performance problems (esp. when really called over the wire). Experienced developers would use the facade pattern to provide a very coarse-grained interface to the client. This facade would then in turn do multiple calls to different more fine-grained methods. All in all, this greatly reduced the number of method calls required and increased performance.

    0 讨论(0)
  • 2020-11-29 19:54

    Suppose you've a abstract Shape class with a (generic/abstracted) drawing functionality and a Circle who implements the Shape. Bridge pattern simply is a two-way abstraction approach to decouple the implementation ( drawing in Circle ) and generic/abstracted functionality ( drawing in the Shape class ).

    What does it really mean? At a first glance, it sounds like a something you already making ( by dependency inversion). So no worries about having a less-ridig or more modular code base. But it's a bit deeper philosophy behind it.

    From my understanding, the need of usage pattern might emerge when I need to add new classes which are closely related with the current system ( like RedCircle or GreenCircle ) and which they differ by only a single functionality ( like color ). And I'm gonna need Bridge pattern particularly if the existing system classes ( Circle or Shape ) are to be frequently changed and you don't want newly added classes to be affected from those changes. So that's why the generic drawing functionality is abstracted away into a new interface so that you can alter the drawing behaviour independent from Shape or Circle.

    0 讨论(0)
提交回复
热议问题