// 패턴 적용
// 2. 변하는 것을 '클래스화' 하자.
// -- Strategy pattern (전략패턴)
// 2.1 인터페이스를 설계하자.
- interface IValidator {
- boolean validate(char c);
- }
- class DigitOnlyValidator implements IValidator {
- @Override
- public boolean validate(char c) {
- return Character.isDigit(c);
- }
- }
- class AllPassValidator implements IValidator {
- @Override
- public boolean validate(char c) {
- return true;
- }
- }
- class LineEdit2 {
- private JFrame frame;
- private StringBuilder builder = new StringBuilder();
- private IValidator iValidator;
- public void setValidator(IValidator iv) {
- iValidator = iv;
- }
- public LineEdit2() {
- frame = new JFrame();
- frame.setSize(300, 200);
- frame.setTitle("EditBox");
- iValidator = new AllPassValidator(); //default
- Container cp = frame.getContentPane();
- cp.setLayout(new FlowLayout());
- final JLabel label = new JLabel("");
- cp.add(label);
- frame.addKeyListener(new KeyListener() { //inner class
- @Override
- public void keyTyped(KeyEvent e) { //키를 입력했다. (Press + Release)
- char c = e.getKeyChar();
- System.out.println(c);
- if(c == '\n') {
- builder = new StringBuilder();
- label.setText("");
- }
- if(iValidator.validate(c)) {
- builder.append(c);
- label.setText(builder.toString());
- }
- }
- @Override
- public void keyReleased(KeyEvent e) {} // 키를 뗐다.
- @Override
- public void keyPressed(KeyEvent e) {} // 키를 눌렀다.
- });
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 프로세스 종료시
- }
- public boolean validate(char c) {
- return Character.isDigit(c);
- }
- public void show() {
- frame.setVisible(true);
- }
- }
- public class Ex2 {
- public static void main(String...args) {
- LineEdit2 lineEdit2 = new LineEdit2();
- lineEdit2.setValidator(new DigitOnlyValidator());
- lineEdit2.show();
- }
- }
'java > design_pattern' 카테고리의 다른 글
Decorator Pattern (0) | 2014.06.27 |
---|---|
Composite Pattern (0) | 2014.06.27 |
Template Method Pattern (0) | 2014.06.27 |
Adapter 패턴 (0) | 2014.06.27 |
Java Singleton 선언하는법 (0) | 2014.06.18 |