design pattern #6 Structural pattern - Adapter

  • 예제 처럼  US  power plug 가 German power outlet 에 맞지 않아 adapter 를 끼우는 것이다.
  • 두 object 사이에 wrapper 역할을 한다. legacy code 를 처리하는데도 씌인다.
  • 예제에서는 SqurePeg 이 RoundHole 에 fit  한지를 체크하기 위해 Adapter 를 도입한다.
  • Adapter 는 RoundPeg  을 extend 해서 getRadius  를 Override 한다.
public class RoundHole {
private double radius;

public RoundHole(double radius) {
this.radius = radius;
}

public double getRadius() {
return radius;
}

public boolean fits(RoundPeg peg) {
boolean result;
result = (this.getRadius() >= peg.getRadius());
return result;
}
}

public class RoundPeg {
private double radius;

public RoundPeg(double radius) {
this.radius = radius;
}

public double getRadius() {
return radius;
}
}
public class SquarePeg {
private double width;

public SquarePeg(double width) {
this.width = width;
}

public double getWidth() {
return width;
}

public double getSquare() {
double result;
result = Math.pow(this.width, 2);
return result;
}
}


public class SquarePegAdapter extends RoundPeg {
private SquarePeg peg;

public SquarePegAdapter(SquarePeg peg) {
this.peg = peg;
}

@Override
public double getRadius() {
double result;
// Calculate a minimum circle radius, which can fit this peg.
result = (Math.sqrt(Math.pow((peg.getWidth() / 2), 2) * 2));
return result;
}
}

public class Demo {
public static void main(String[] args) {
// Round fits round, no surprise.
RoundHole hole = new RoundHole(5);
RoundPeg rpeg = new RoundPeg(5);
if (hole.fits(rpeg)) {
System.out.println("Round peg r5 fits round hole r5.");
}

SquarePeg smallSqPeg = new SquarePeg(2);
SquarePeg largeSqPeg = new SquarePeg(20);
// hole.fits(smallSqPeg); // Won't compile.

// Adapter solves the problem.
SquarePegAdapter smallSqPegAdapter = new SquarePegAdapter(smallSqPeg);
SquarePegAdapter largeSqPegAdapter = new SquarePegAdapter(largeSqPeg);
if (hole.fits(smallSqPegAdapter)) {
System.out.println("Square peg w2 fits round hole r5.");
}
if (!hole.fits(largeSqPegAdapter)) {
System.out.println("Square peg w20 does not fit into round hole r5.");
}
}
}

Comments

Popular posts from this blog

삼성전자 무선사업부 퇴사 후기

코드리뷰에 대하여

개발자 커리어로 해외 취업, 독일 이직 프로세스