1. 내가 설계한 Command pattern 예제

제목 : 돌려 돌려 선풍기

Command pattern이란 classobject들이 상호작용하는 방법과 책임을 분산하는 방법을 정의한 것이다. 여러 가지 행위 관련 pattern을 사용하여 독립적으로 일을 처리하고자 할 때 사용한다.

이번 과제에서 내가 설계한 Command patern예제는 선풍기이다. 선풍기는 바람을 일으키는 기능 이외에 회전이라는 별도의 기능이 따로 있다. 그렇기 때문에 이번 과제인 Command pattern예제로 선정하였다. 선풍기 프로그램의 클래스는 총 7가지이다. 하나하나 살펴보겠다.

 

 

1) client클래스

client클래스는 프로그램이 처음 시작하는 클래스이다. client클래스에서 바람을 일으키는 button1과 회전을 시키는 button2를 생성하여 이용자는 pressed()함수를 이용하여 해당 버튼의 기능을 수행한다.

public class client {

public static void main(String[] args){

Wind wind = new Wind();

Command WindCommand = new WindCommand(wind);

Button button1 = new Button(WindCommand);

 

Rotation rotation = new Rotation();

Command RotationCommand = new RotationCommand(rotation);

Button button2 = new Button(RotationCommand);

 

button1.pressed();

button2.pressed();

button2.pressed();

button1.pressed();

button1.pressed();

}

}



 

2) Button클래스

Button클래스는 setCommand함수를 이용하여 어떤 버튼을 생성할 것인가에 대해 Command클래스를 설정 할 수 있고 pressed()함수를 이용하여 기능을 실행시킨다.

public class Button {

private Command theCommand;

public Button(Command theCommand){

setCommand(theCommand);

}

public void setCommand(Command newCommand){

this.theCommand = newCommand;

}

public void pressed(){

theCommand.execute();

}

}

 

 

 

3) Command클래스

각 기능의 Command를 수행시키는 매개체 역할을 하는 클래스이다.

public interface Command {

public abstract void execute();

}

 

 

 

4) WindCommand클래스

Command클래스를 상속받고 Wind클래스를 이용하여 execute()함수를 통해 바람을 일이키는 기능을 수행시키는 클래스이다.

public class WindCommand implements Command{

private Wind wind;

public WindCommand(Wind wind){

this.wind = wind;

}

public void execute(){

wind.start();

}

}

 

 

 

5) RotationCommand클래스

Command클래스를 상속받고 Rotation클래스를 이용하여 execute()함수를 통해 회전기능을 수행시키는 클래스이다.

public class RotationCommand implements Command{

private Rotation rotation;

public RotationCommand(Rotation rotation){

this.rotation = rotation;

}

public void execute(){

rotation.start();

}

}

 

 

 

6) Wind클래스

start()함수를 이용하여 power변수에 따라서 해당하는 기능을 수행한다.

power=0일 때, power1증가시키고 바람세기를 약으로 선풍기를 가동시킨다.

power=1일 때, power1증가시키고 바람세기를 강으로 선풍기를 가동시킨다.

power=2일 때, power0으로 초기화하고 선풍기를 중지시킨다.

public class Wind {

private int power = 0;

public void start(){

if(power == 0){

power++;

System.out.println("선풍기 가동 (바람세기:)");

}else if(power == 1){

power++;

System.out.println("선풍기 가동 (바람세기:)");

}else{

power =0;

System.out.println("선풍기 가동 중지");

}

}

}

 

 

 

7) Rotation클래스

start()함수를 이용하여 run변수에 따라서 해당하는 기능을 수행한다.

run=false일 때, runtrue로 바꾸고 선풍기를 회전시킨다.

run=true일 때, runfalse로 바꾸고 선풍기 회전을 중지시킨다.

public class Rotation {

private boolean run=false;

public void start(){

if(run==false){

run = true;

System.out.println("선풍기를 회전시킵니다.");

}else{

System.out.println("선풍기 회전을 중지시킵니다.");

run = false;

}

}

}

 


2. 선풍기 클래스다이어그램



 

3. 실행화면

button1.pressed(); #button1=바람

button2.pressed(); #button2=회전

button2.pressed();

button1.pressed();

button1.pressed();

 

+ Recent posts