2015년 7월 9일 목요일

Java MVC model

Observer
public interface Observer {
   public void update(int data);
}

Model
public class CalculatorModel {
 private int data;
 private ArrayList list = new ArrayList();
 
 public void addTwoNumber(int firstNumber, int secondNumber){
  data = firstNumber + secondNumber;
  notifyObservers();
 }
 
 public void registerObserver(Observer o){
  list.add(o);
 }
 
 public void notifyObservers() {
  for(Observer o : list){
   o.update(data);   
  }  
 }
}

Controller
public class CalculatorController implements ActionListener{
 private CalculatorModel model;
 private CalculatorView view;

 public CalculatorController(CalculatorModel model, CalculatorView view) {
  this.model = model;
  this.view = view;
  this.view.setCalculatorListener(this);
 }

 @Override
 public void actionPerformed(ActionEvent arg0) {
  try {
   int firstNumber = view.getFirstNumber();
   int secondNumber = view.getSecondNumber();
   model.addTwoNumber(firstNumber, secondNumber);
  } catch (RuntimeException e) {
   e.printStackTrace();
  }
 }
}

View
public class CalculatorView extends JFrame implements Observer{
 private JTextField firstNumber = new JTextField(10);
 private JLabel additionLabel = new JLabel("+");
 private JTextField secondNumber = new JTextField(10);
 private JButton calculateButton = new JButton("계산");
 private JTextField calcSolution = new JTextField(10);
 private JPanel calcPanel = new JPanel();

 public CalculatorView() {
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setSize(600, 200);
  setLayout(new BorderLayout());
  calcPanel.add(firstNumber);
  calcPanel.add(additionLabel);
  calcPanel.add(secondNumber);
  calcPanel.add(calculateButton);
  calcPanel.add(calcSolution);
  add(calcPanel, BorderLayout.CENTER);
 }

 public int getFirstNumber() {
  return Integer.parseInt(firstNumber.getText());
 }

 public int getSecondNumber() {
  return Integer.parseInt(secondNumber.getText());
 }

 public void setCalcSolution(int result) {
  calcSolution.setText(result +"");
 }

 public void setCalculatorListener(ActionListener listener){
  calculateButton.addActionListener(listener);
 }

 @Override
 public void update(int data) {
  setCalcSolution(data);
 }
}

Main Method
public class MVCTest {
 public static void main(String[] args) {
  CalculatorView view = new CalculatorView();
  CalculatorModel model = new CalculatorModel();
  model.registerObserver(view);
  
  @SuppressWarnings("unused")
  CalculatorController controller = new CalculatorController(model, view);
  view.setVisible(true);
 }
}

댓글 없음:

댓글 쓰기