mercredi 21 juin 2017

Why saying that Memento Design Pattern isn't violating the encapsulation?

Why saying that Memento is doing its job without violates the encapsulation, while I can implement the simple way but also without violate the encapsulation? What is the use of Memento? I have a sample program, which will save the student details while user press the save button, and undo the action when user press then undo button.
Sample code below is implementation without using Memento pattern:
Student.java

public class Student
{
    private String name;
    private String gender;
    private int age;
    private Contact contact;

    public Student(String name, String gender, int age, Contact contact)
    {
        this.name = name;
        this.gender = gender;
        this.age = age;
        this.contact = contact;
    }
    //getter and setter
}

Main.java

public class Main extends javax.swing.JFrame implements DocumentListener
{
    private Student sCopy, student;

    private void btnUndoActionPerformed(java.awt.event.ActionEvent evt)                                        
    {                                            
        txtName.setText(sCopy.getName());
        txtGender.setText(sCopy.getGender());
        txtAge.setText(sCopy.getAge() + "");
        txtPhone.setText(sCopy.getContact().getPhoneNo());
        txtEmail.setText(sCopy.getContact().getEmail());
        txtAddress.setText(sCopy.getContact().getAddress());
        student = sCopy;
    }                                       

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt)                                        
    {                                            
        sCopy = student;
        Contact c = new Contact(txtPhone.getText(), txtEmail.getText(), txtAddress.getText());
        student = new Student(txtName.getText(), txtGender.getText(), Integer.parseInt(txtAge.getText()), c);
    }    

Sample code above works perfectly, but why we need memento while it can be done so easily? I don't see where the implementation above violets the encapsulation...

Aucun commentaire:

Enregistrer un commentaire