when do we need Adapter pattern?

后端 未结 6 846
耶瑟儿~
耶瑟儿~ 2020-12-13 04:37

When do we need to go for Adapter pattern? If possible give me a real world example that suits that pattern...

6条回答
  •  攒了一身酷
    2020-12-13 05:00

    Existing Interface

    interface Shape {
        public int calculateArea(int r);
    }
    

    Current Implementation for Shape interface

    class Square implements Shape {
        @Override
        public int calculateArea(int r) {
            return r * r;
        }
    }
    

    Now Consider that you want Circle class to adapt to our existing interface which in no way we can modify (Written by third party).

    class Circle {
        public double calculateCircularArea (int r) {
            return 3.14 * r * r;
        }
    }
    

    Now we have adapt Circle implementation to our Shape interface. So we need an adaptor as they are incompatible.

    class CirCleAdaptor extends Circle implements Shape {
        @Override
        public int calculateArea(int r) {
            return (int) calculateCircularArea(r);
        }
    }
    

    CircleAdaptor - Is the Adaptor for Circle
    Circle - Is the Adaptee
    Shape - Is the Target Interface

    public class AdapterPattern {
        public static void main(String[] args) {
            Shape circle = new CirCleAdaptor();
            System.out.println("Circle Area " + circle.calculateArea(5));
            Shape square = new Square();
            System.out.println("Square Area " + square.calculateArea(5));
        }
    }
    

    Hope this gives a better idea about When to use it.

提交回复
热议问题