본문 바로가기

Development/Programming

[Java Design Patten] Balking 패턴

지금 이 처리를 실행하면 곤란하다거나 혹은 당장 실행할 필요가 없거나 혹은 다른 곳에서 이미 처리를 하고 있는 경우 실행을 중단하고 돌아가는 패턴이다.


   가드 되어 있는 객체 역할 이며 guardedMethod와 stateChangingMethod 를 가지고 있는 패턴이다. 여기서는 save와 chage 함수를 보면 된다.

public class Data {

private final String filename;

private String content;

private boolean changed;

public Data (final String filename, final String content) {

this.filename = filename;

this.content = content;

this.changed = changed;

}

public synchronized void change (final String newContent) {

this.content = newContent;

this.changed = true;

}

public synchronized void save () throws IOException {

if (!this.changed) {

return;

}//end if

doSave();

this.changed = false;

}

private void doSave () throws IOException {

System.out.println(Thread.currentThread().getName() + "Calls doSave, content = " + this.content);

Writer writer = new FileWriter(filename);

writer.write(content);

writer.close();

}

}



public class SaverThread extends Thread {

private final Data data;

public SaverThread (final String name, final Data data) {

super(name);

this.data = data;

}

public void run () {

try {

while (true) {

data.save();

Thread.sleep(1000);

}

} catch (final IOException e) {

e.printStackTrace();

} catch (final InterruptedException e) {

e.printStackTrace();

}

}

}



public class ChangerThread extends Thread {

private final Data data;

private final Random random = new Random();

public ChangerThread (final String name, final Data data) {

super(name);

this.data = data;

}

public void run () {

try {

for (int i=0;true;i++) {

data.change("NO." + i);

Thread.sleep(random.nextInt(1000));

data.save();

}//end for

} catch (final IOException e) {

e.printStackTrace();

} catch (final InterruptedException e) {

e.printStackTrace();

}

}

}


public class Main {

public static void main (final String[] args) {

final Data data = new Data("text.txt","(empty)");

new ChangerThread("ChageThread", data).start();

new SaverThread("SaverThread", data).start();

}

}