You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Structural Patterns provide different ways to create a class structure, for example using inheritance and composition
221
221
to create a large object from small objects.
222
+
223
+
### Adapter Pattern
224
+
225
+
This pattern is used in such a way that two unrelated interfaces can work together. The object that joins these unrelated interfaces is called Adapter. As a real life example, we can think of a mobile charger as an adapter because mobile battery needs 3 Volts to charge but the normal socket produces either 120V (US) or 240V (India). So the mobile charger works as an adapter between mobile charging socket and the wall socket.
226
+
First of all we'll have two classes : Volt - to measure volts) and Socket :
227
+
228
+
```java
229
+
230
+
publicclassVolt {
231
+
privateint volts;
232
+
publicVolt(intv){
233
+
this.volts=v;
234
+
}
235
+
publicintgetVolts() {
236
+
return volts;
237
+
}
238
+
publicvoidsetVolts(intvolts) {
239
+
this.volts = volts;
240
+
}
241
+
}
242
+
243
+
244
+
publicclassSocket {
245
+
publicVoltgetVolt(){
246
+
returnnewVolt(120);
247
+
}
248
+
249
+
}
250
+
```
251
+
Now we want to build an adapter that can produce 3 volts, 12 volts and default 120 volts. So first of all we will create an adapter interface with these methods.
252
+
253
+
```java
254
+
publicinterfaceSocketAdapter {
255
+
publicVoltget120Volt();
256
+
publicVoltget12Volt();
257
+
publicVoltget3Volt();
258
+
}
259
+
260
+
```
261
+
262
+
while implementing this pattern, there are two approaches : one that deals with inheritance and another one that deals with Composition.Note that they are almost the same thus, here we'll deal with one with inheritance. Let's implement out adapter class !
0 commit comments