Статьи

Посредник адаптера представления модели Java Swing

Обычно я создаю свои Java-приложения на основе Spring Framework . Однако недавно меня попросили реализовать настольное Java-приложение для клиента с использованием независимой от языка инфраструктуры MVC — PureMVC , поэтому ниже приведена демонстрационная реализация демонстрации сотрудника-администратора для PureMVC в Java Swing. Если вы хотите следовать, демо-версия доступна на GitHub. Java Swing MVA Демо

Архитектурное Резюме

Это приложение использует интересную вариацию общего шаблона MVC, называемого шаблоном Model View Adapter (MVA). Модель адаптера модельного представления наиболее известна благодаря умному продвижению слабой связи между компонентами представления путем введения уровня косвенности для разделения проблем и обеспечения обмена сообщениями через посредник и простой интерфейс адаптера. Используя объекты-значения и прокси-объекты, посредники могут направлять изменения сообщений на уровень модели без прямой привязки к объектам домена. Несмотря на то, что для этой реализации требуется немного больше стандартного кода, этот гибридный дизайн поддерживает модульный стиль, который довольно легко понять и поддерживать.

Реализация дизайна приложения

Если вы не знакомы с созданием настольных приложений в Swing, учебник по Swing может помочь вам освоиться с основными концепциями или вы можете просто загрузить пример приложения и просмотреть его по мере продвижения.

Поскольку это классическое приложение Java Swing, я начну с создания базового фрейма в качестве точки входа, содержащей три основные панели, и инициализирую ApplicationFacade в украшенном методе startup чтобы отделить поток приложения от потока диспетчеризации событий GUI.

На следующей диаграмме объектов показано, как класс EmployeeAdmin создает три основных компонента, а затем вызывает метод startup .

ява-свинг-MVA-приложение-INIT

Порядок здесь довольно прост. Сначала создайте базовый кадр, затем три основных компонента, инициализируйте ApplicationFacade, а затем запустите базовый кадр.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
package employeeadmin;
 
import api.Utils.GBC;
import employeeadmin.view.components.RolePanel;
import employeeadmin.view.components.UserForm;
import employeeadmin.view.components.UserList;
 
import javax.swing.*;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import java.awt.GridBagLayout;
 
/**
 * @author Edward Beckett
 */
public class EmployeeAdmin extends JFrame implements Runnable {
 
    private UserList userList;
    private UserForm userForm;
    private RolePanel rolePanel;
 
    public EmployeeAdmin() {
        build();
    }
 
    private void build() {
        setTitle( "Java Swing Model View Adapter (MVA) Demo" );
        setLayout( new GridBagLayout() );
        setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
        setResizable( false );
        buildComponents();
        startup();
        pack();
        setLocationRelativeTo( null );
        setVisible( true );
    }
 
    private void buildComponents() {
 
        JPanel basePanel = new JPanel( new GridBagLayout() );
 
        userList = new UserList();
        userForm = new UserForm();
        rolePanel = new RolePanel();
 
        GBC userListConstraints = new GBC( 0, 0, 2, 1 )
            .setWeight( 1, 1 ).setAnchor( GBC.NORTH ).setFill( GBC.BOTH ).setInsets( 0, 0, 0, 0 ).setIpad( 0, 0 );
        basePanel.add( userList, userListConstraints );
 
        GBC userFormConstraints = new GBC( 0, 1, 1, 1 ).setWeight( 1, .5 )
            .setAnchor( GBC.LINE_START )
            .setFill( GBC.BOTH )
            .setInsets(
                0, 0, 0, 0 )
            .setIpad( 0, 0 );
        basePanel.add( userForm, userFormConstraints );
 
        GBC rolePanelConstraints = new GBC( 1, 1, 1, 1 )
            .setWeight( 1, .5 )
            .setAnchor( GBC.LINE_END )
            .setFill( GBC.BOTH )
            .setInsets( 0, 0, 0, 0 )
            .setIpad( 0, 0 );
        basePanel.add( rolePanel, rolePanelConstraints );
 
        GBC basePanelConstraints = new GBC( 0, 0, 1, 1 ).setWeight( 1, 1 )
            .setFill( GBC.BOTH )
            .setAnchor( GBC.CENTER )
            .setInsets( 0, 0, 0, 0 )
            .setIpad( 0, 0 );
        add( basePanel, basePanelConstraints );
    }
 
    protected void startup() {
        ApplicationFacade.getInstance().startup( this );
    }
 
    public static void main( String... args ) {
        try {
            UIManager.setLookAndFeel( new NimbusLookAndFeel() );
        } catch( UnsupportedLookAndFeelException e ) {
            e.printStackTrace();
        }
        new EmployeeAdmin().run();
    }
 
    @Override
    public void run() {
        SwingUtilities.invokeLater( () -> {
            //go.
        } );
    }
 
    public UserList getUserList() {
        return userList;
    }
 
    public UserForm getUserForm() {
        return userForm;
    }
 
    public RolePanel getRolePanel() {
        return rolePanel;
    }
 
}

После запуска кадра ApplicationFacade отвечает за инициализацию командного контроллера, регистрирующего несколько команд для полной инициализации приложения.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package employeeadmin;
 
import employeeadmin.controller.AddRoleResultCommand;
import employeeadmin.controller.DeleteUserCommand;
import employeeadmin.controller.StartupCommand;
import org.puremvc.java.multicore.patterns.facade.Facade;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/7/2015
 */
public class ApplicationFacade extends Facade {
 
    public static final String STARTUP = "startup";
    public static final String NEW_USER = "newUser";
    public static final String DELETE_USER = "deleteUser";
    public static final String CANCEL_SELECTED = "cancelSelected";
    public static final String USER_SELECTED = "userSelected";
    public static final String USER_ADDED = "userAdded";
    public static final String USER_UPDATED = "userUpdated";
    public static final String USER_DELETED = "userDeleted";
    public static final String INIT_USERS = "initUsers";
    public static final String ADD_ROLE = "addRole";
    public static final String ADD_ROLE_RESULT = "addRoleResult";
    private static ApplicationFacade instance;
 
    public static final String NAME = "ApplicationFacade";
 
    public static ApplicationFacade getInstance() {
        if( instance == null ) {
            instance = new ApplicationFacade();
        }
        return instance;
    }
 
    protected ApplicationFacade() {
        super( NAME );
    }
 
    public void startup( Object app ) {
        sendNotification( STARTUP, app );
 
    }
 
    @Override
    protected void initializeController() {
        super.initializeController();
        registerCommand( STARTUP, new StartupCommand() );
        registerCommand( DELETE_USER, new DeleteUserCommand() );
        registerCommand( ADD_ROLE_RESULT, new AddRoleResultCommand() );
 
    }
 
}

Первая команда, StartupCommand , в свою очередь, запускает еще две PrepViewCommand , PrepViewCommand и PrepModelCommand . Две другие команды, DeleteUserCommand и AddRoleResultCommand являются просто вспомогательными классами прокси.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
package employeeadmin.controller;
 
import org.puremvc.java.multicore.patterns.command.MacroCommand;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/2/2015
 */
public class StartupCommand extends MacroCommand {
 
    @Override
    public final void initializeMacroCommand() {
 
        addSubCommand( new PrepViewCommand() );
        addSubCommand( new PrepModelCommand() );
    }
 
}

PrepViewCommand регистрирует посредники для всех компонентов представления.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package employeeadmin.controller;
 
import employeeadmin.EmployeeAdmin;
import employeeadmin.view.RolePanelMediator;
import employeeadmin.view.UserFormMediator;
import employeeadmin.view.UserListMediator;
import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.command.SimpleCommand;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/5/2015
 */
public class PrepViewCommand extends SimpleCommand {
 
    @Override
    public final void execute( INotification notification ) {
        EmployeeAdmin employeeAdmin = (EmployeeAdmin) notification.getBody();
 
        getFacade().registerMediator( new UserListMediator( employeeAdmin.getUserList() ) );
        getFacade().registerMediator( new UserFormMediator( employeeAdmin.getUserForm() ) );
        getFacade().registerMediator( new RolePanelMediator( employeeAdmin.getRolePanel() ) );
 
    }
 
}

PrepModelCommand создает начальную модель домена, регистрирует прокси-объекты DAO, а затем завершает жизненный цикл запуска приложения.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package employeeadmin.controller;
 
import employeeadmin.ApplicationFacade;
import employeeadmin.model.RoleProxy;
import employeeadmin.model.UserProxy;
import employeeadmin.model.enums.Department;
import employeeadmin.model.enums.Role;
import employeeadmin.model.vo.RoleVO;
import employeeadmin.model.vo.UserVO;
import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.command.SimpleCommand;
 
import java.util.Arrays;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/5/2015
 */
public class PrepModelCommand extends SimpleCommand {
 
    @Override
    public final void execute( final INotification notification ) {
        UserProxy userProxy = new UserProxy();
        RoleProxy roleProxy = new RoleProxy();
 
        //@formatter:off
        RoleVO larryRoles = new RoleVO( "lstooge", Arrays.asList( Role.PAYROLL, Role.EMP_BENEFITS ) );
        RoleVO moeRoles = new RoleVO( "mstooge",Arrays.asList( Role.INVENTORY, Role.PRODUCTION, Role.SALES, Role.SHIPPING ) );
        RoleVO curlyRoles = new RoleVO( "cstooge", Arrays.asList( Role.ACCT_PAY, Role.ACCT_RCV, Role.GEN_LEDGER ) );
 
        userProxy.addUser(new UserVO( "lstooge", "Larry", "Stooge", "larry@stooges.com", "ijk456", Department.ACCT.getValue() ) );
        userProxy.addUser(new UserVO( "mstooge", "Moe", "Stooge", "moe@stooges.com", "abc123", Department.PLANT.getValue() ) );
        userProxy.addUser(new UserVO( "cstooge", "Curly", "Stooge", "curly@stooges.com", "xyz987", Department.SALES.getValue() ) );
        //@formatter:on
 
        roleProxy.addRole( larryRoles );
        roleProxy.addRole( moeRoles );
        roleProxy.addRole( curlyRoles );
 
        getFacade().registerProxy( userProxy );
        getFacade().registerProxy( roleProxy );
 
        getFacade().sendNotification( ApplicationFacade.INIT_USERS, userProxy, "UserProxy" );
        getFacade().removeCommand( ApplicationFacade.STARTUP );
    }
 
}

Уровень просмотра

Это приложение имеет три сотрудничающих компонента. UserList , UserForm и RolePanel . Каждый компонент содержит все необходимые подкомпоненты, атрибуты и операции как для функции, так и для управления состоянием независимо от внешних компонентов, связывается с mediator через messaging adapter interface и получает сообщение непосредственно от mediator . Я расскажу больше на эту тему в разделе Адаптер обмена сообщениями.

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package employeeadmin.view.components;
 
import api.Utils.BorderBuilder;
import api.Utils.GBC;
import api.Utils.UnhandledException;
import employeeadmin.model.vo.UserVO;
import employeeadmin.view.interfaces.UserListMessage;
 
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/3/2015
 */
public class UserList extends JPanel implements ActionListener, ListSelectionListener {
 
    public static final String NEW_USER = "New";
    public static final String NEW_USER_LABEL = "New";
    public static final String DELETE_USER = "Delete";
    public static final String DELETE_USER_LABEL = "Delete";
 
    UserListMessage message;
 
    private UserTable userTable;
    private JPanel buttonPanel;
    private JButton newUserButton;
    private JButton deleteUserButton;
    private JScrollPane userPane;
    private JTableHeader header;
    private ArrayList users;
    private UserVO user;
 
    public UserList() {
        setLayout( new GridBagLayout() );
        setBorder( new BorderBuilder( "Users", TitledBorder.LEFT, TitledBorder.DEFAULT_POSITION, 2, Font.BOLD, 12 ) );
        initComponents();
    }
 
    public class UserTable extends JTable {
 
        public UserTable() {
            super( new UserListModel() );
            setBackground( new Color( 235, 235, 235 ) );
        }
 
        @Override
        public UserListModel getModel() {
            return (UserListModel) super.getModel();
        }
    }
 
    public static class UserListModel extends AbstractTableModel {
 
        private final String[] columnName = { "Username", "First Name", "Last Name", "Email", "Department" };
        private final Class<?>[] columnType = { String.class, String.class, String.class, String.class, String
            .class };
 
        private ArrayList users;
 
        private static final int COLUMN_USERNAME = 0;
        private static final int COLUMN_FIRST_NAME = 1;
        private static final int COLUMN_LAST_NAME = 2;
        private static final int COLUMN_EMAIL = 3;
        private static final int COLUMN_DEPARTMENT = 4;
 
        public UserListModel() {}
 
        public void reload( ArrayList users ) {
            this.users = users;
            fireTableDataChanged();
        }
 
        @Override
        public Class<?> getColumnClass( int column ) {
            return columnType[column];
        }
 
        @Override
        public int getColumnCount() {
            return columnName.length;
        }
 
        @Override
        public String getColumnName( int column ) {
            return columnName[column];
        }
 
        @Override
        public int getRowCount() {
            if( users == null ) {
                return 0;
            }
            return users.size();
        }
 
        @Override
        public Object getValueAt( int row, int column ) {
            if( users.get( row ) != null ) {
                UserVO user = users.get( row );
                switch( column ) {
                    case COLUMN_USERNAME:
                        if( user.username != null ) {
                            return user.username;
                        }
                    case COLUMN_FIRST_NAME:
                        if( user.firstName != null ) {
                            return user.firstName;
                        }
                    case COLUMN_LAST_NAME:
                        if( user.lastName != null ) {
                            return user.lastName;
                        }
                    case COLUMN_EMAIL:
                        if( user.email != null ) {
                            return user.email;
                        }
                    case COLUMN_DEPARTMENT:
                        if( user.department != null ) {
                            return user.department;
                        }
                    default:
                        return null;
                }
            }
            return null;
        }
 
        @Override
        public boolean isCellEditable( int rowIndex, int columnIndex ) {
            return false;
        }
    }
 
    private void initComponents() {
 
        userTable = new UserTable();
        userTable.getSelectionModel().addListSelectionListener( this );
 
        buttonPanel = new JPanel();
 
        deleteUserButton = new JButton();
        deleteUserButton.addActionListener( this );
 
        newUserButton = new JButton();
        newUserButton.addActionListener( this );
 
        userPane = new JScrollPane();
 
        userPane.getViewport().setBackground( new Color( 241, 241, 241 ) );
        userTable.getColumnModel().getColumn( 0 ).setPreferredWidth( 100 );
        userTable.getColumnModel().getColumn( 1 ).setPreferredWidth( 100 );
        userTable.getColumnModel().getColumn( 2 ).setPreferredWidth( 100 );
        userTable.getColumnModel().getColumn( 3 ).setPreferredWidth( 100 );
        userTable.getColumnModel().getColumn( 4 ).setPreferredWidth( 100 );
 
        userTable.setRowHeight( 16 );
        userTable.setShowGrid( true );
        userTable.setVisible( true );
        userTable.setFillsViewportHeight( true );
        userTable.setGridColor( Color.LIGHT_GRAY );
        userTable.setShowHorizontalLines( true );
        userTable.setShowVerticalLines( true );
        userTable.setFont( new Font( "Segoe UI", Font.PLAIN, 12 ) );
        userTable.setAutoResizeMode( JTable.AUTO_RESIZE_ALL_COLUMNS );
        userTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
 
        header = userTable.getTableHeader();
        header.setFont( new Font( "Segoe UI", Font.BOLD, 12 ) );
 
        userPane.setPreferredSize( new Dimension( 600, 200 ) );
        userPane.setViewportView( userTable );
 
        //@formatter:off
        GBC userPaneConstraints = new GBC( 0, 0, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.CENTER ).setFill( GBC.BOTH ) .setInsets(
            0, 0, 0, 0 ) .setIpad( 0, 0 );
        add( userPane, userPaneConstraints );
 
        GBC buttonPanelConstraints = new GBC( 0, 1, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ).setFill( GBC.BOTH ) .setInsets( 0, 0, 0, 0 ) .setIpad( 0, 0 );
        add( buttonPanel, buttonPanelConstraints );
        //@formatter:on
 
        buttonPanel.setLayout( new FlowLayout( FlowLayout.LEADING ) );
        newUserButton.setText( NEW_USER_LABEL );
        newUserButton.setToolTipText( "Click to add a new user." );
        deleteUserButton.setText( DELETE_USER_LABEL );
        deleteUserButton.setToolTipText( "Click to delete the selected user" );
        buttonPanel.add( newUserButton );
        buttonPanel.add( deleteUserButton );
    }
 
    @Override
    public void actionPerformed( ActionEvent e ) {
        switch( e.getActionCommand() ) {
            case NEW_USER:
                cancelSelection();
                message.onNew();
                break;
            case DELETE_USER:
                if( getUser() != null ) {
                    if( JOptionPane.showConfirmDialog( null, "Delete User?", "Delete User?",
                        JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE ) == 0 ) {
                        message.onDelete( user );
                    }
                }
                break;
            default:
                throw new UnhandledException( "Error Unhandled event [" + e.getID() + "]" );
        }
 
    }
 
    @Override
    public void valueChanged( ListSelectionEvent e ) {
        if( userTable.getSelectedRow() > -1 && !e.getValueIsAdjusting() ) {
            UserVO user = getUsers().get( userTable.getSelectedRow() );
            setUser( user );
            message.onSelect( user );
        }
    }
 
    public void cancelSelection() {
        this.user = null;
        userTable.getSelectionModel().clearSelection();
        deleteUserButton.setEnabled( false );
    }
 
    public void reloadUsers( ArrayList users ) {
        this.users = users;
        userTable.getModel().reload( users );
        cancelSelection();
    }
 
    public void addUser( UserVO user ) {
        getUsers().add( user );
        userTable.getModel().reload( users );
    }
 
    public void setUser( UserVO user ) {
        this.user = user;
        deleteUserButton.setEnabled( true );
    }
 
    public UserVO getUser() {
        return ( this.user == null ? new UserVO() : this.user );
    }
 
    public ArrayList getUsers() {
        return users;
    }
 
    public void setMessage( UserListMessage message ) {
        this.message = message;
    }
}
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
package employeeadmin.view.components;
 
import api.Utils.BorderBuilder;
import api.Utils.GBC;
import api.Utils.UnhandledException;
import employeeadmin.model.enums.Department;
import employeeadmin.model.vo.RoleVO;
import employeeadmin.model.vo.UserVO;
import employeeadmin.view.interfaces.UserFormMessage;
 
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 1/29/2015
 */
public class UserForm extends JPanel implements ActionListener {
 
    public static final int MODE_ADD = 1;
    public static final int USER_SELECTED = 2;
    public static final int MODE_UPDATE = 3;
    public static final int DELETE_USER = 4;
    public static final int FORM_ENABLED = 5;
    public static final int FORM_DISABLED = 6;
 
    private static final String FIRST_NAME = "First Name";
    private static final String LAST_NAME = "Last Name";
    private static final String EMAIL = "Email";
    private static final String USERNAME = "Username *";
    private static final String PASSWORD = "Password *";
    private static final String CONFIRM = "Confirm Password *";
    private static final String DEPARTMENT = "Department *";
    private static final String SAVE_PROFILE = "Save Profile";
    private static final String UPDATE_PROFILE = "Update Profile";
    private static final String CANCEL = "Cancel";
 
    private JLabel firstNameLabel;
    private JLabel lastNameLabel;
    private JLabel emailLabel;
    private JLabel userNameLabel;
    private JLabel passwordLabel;
    private JButton cancelButton;
    private JLabel passwordConfirmLabel;
    private JLabel departmentLabel;
    private JTextField firstNameField;
    private JTextField lastNameField;
    private JTextField emailField;
    private JTextField userNameField;
    private JPasswordField passwordField;
    private JPasswordField passwordConfirmField;
    private DefaultComboBoxModel departmentListModel;
    private JComboBox departmentList;
    private JButton updateUserButton;
    private UserVO user;
    private RoleVO roles;
 
    private UserFormMessage message;
 
    public UserForm() {
        setLayout( new GridBagLayout() );
        setBorder(
            new BorderBuilder( "User Profile", TitledBorder.LEFT, TitledBorder.DEFAULT_POSITION, 2, Font.BOLD, 12 ) );
        initComponents();
    }
 
    private void initComponents() {
 
        firstNameLabel = new JLabel( FIRST_NAME );
        lastNameLabel = new JLabel( LAST_NAME );
        emailLabel = new JLabel( EMAIL );
        userNameLabel = new JLabel( USERNAME );
        passwordLabel = new JLabel( PASSWORD );
        passwordConfirmLabel = new JLabel( CONFIRM );
        departmentLabel = new JLabel( DEPARTMENT );
 
        firstNameField = new JTextField();
        firstNameField.addActionListener( this );
 
        lastNameField = new JTextField();
        lastNameField.addActionListener( this );
 
        emailField = new JTextField();
        emailField.addActionListener( this );
 
        userNameField = new JTextField();
        userNameField.addActionListener( this );
 
        passwordField = new JPasswordField();
        passwordField.addActionListener( this );
 
        passwordConfirmField = new JPasswordField();
        passwordConfirmField.addActionListener( this );
 
        departmentListModel = new DefaultComboBoxModel<>();
        Department.list().stream().map( Department:: getValue ).forEach( departmentListModel:: addElement );
        departmentList = new JComboBox<>( departmentListModel );
 
        updateUserButton = new JButton();
        updateUserButton.addActionListener( this );
 
        cancelButton = new JButton( CANCEL );
        cancelButton.addActionListener( this );
 
        //@formatter:off
        GBC firstNameLabelConstraints = new GBC( 0, 0, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(
            0, 0, 0, 10 ) .setIpad( 0, 0 );
        add( firstNameLabel, firstNameLabelConstraints );
 
        GBC lastNameLabelConstraints = new GBC( 0, 1, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(
            0, 0, 0, 10 ) .setIpad( 0, 0 );
        add( lastNameLabel, lastNameLabelConstraints );
 
        GBC emailLabelConstraints = new GBC( 0, 2, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(
            0, 0, 0, 10 ) .setIpad( 0, 0 );
        add( emailLabel, emailLabelConstraints );
 
        GBC userNameLabelConstraints = new GBC( 0, 3, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(
            0, 0, 0, 10 ) .setIpad( 0, 0 );
        add( userNameLabel, userNameLabelConstraints );
 
        GBC passwordLabelConstraints = new GBC( 0, 4, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(
            0, 0, 0, 10 ) .setIpad( 0, 0 );
        add( passwordLabel, passwordLabelConstraints );
 
        GBC passwordConfirmLabelConstraints = new GBC( 0, 5, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ) .setFill(
            GBC.NONE ) .setInsets( 0, 0, 0, 10 ) .setIpad( 0, 0 );
        add( passwordConfirmLabel, passwordConfirmLabelConstraints );
 
        GBC departmentLabelConstraints = new GBC( 0, 6, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(
            0, 0, 0, 10 ) .setIpad( 0, 0 );
        add( departmentLabel, departmentLabelConstraints );
 
        GBC firstNameFieldConstraints = new GBC( 1, 0, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.WEST ).setFill( GBC.HORIZONTAL ) .setInsets(
            0, 0, 0, 0 ) .setIpad( 0, 0 );
        add( firstNameField, firstNameFieldConstraints );
 
        GBC lastNameFieldConstraints = new GBC( 1, 1, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.WEST ).setFill( GBC.HORIZONTAL ) .setInsets(
            0, 0, 0, 0 ) .setIpad( 0, 0 );
        add( lastNameField, lastNameFieldConstraints );
 
        GBC emailFieldConstraints = new GBC( 1, 2, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.WEST ).setFill( GBC.HORIZONTAL ) .setInsets(
            0, 0, 0, 0 ) .setIpad( 0, 0 );
        add( emailField, emailFieldConstraints );
 
        GBC userNameFieldConstraints = new GBC( 1, 3, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.WEST ).setFill( GBC.HORIZONTAL ) .setInsets(
            0, 0, 0, 0 ) .setIpad( 0, 0 );
        add( userNameField, userNameFieldConstraints );
 
        GBC passwordFieldConstraints = new GBC( 1, 4, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.WEST ).setFill( GBC.HORIZONTAL ) .setInsets(
            0, 0, 0, 0 ) .setIpad( 0, 0 );
        add( passwordField, passwordFieldConstraints );
 
        GBC passwordConfirmFieldConstraints = new GBC( 1, 5, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.WEST ).setFill( GBC.HORIZONTAL ) .setInsets(
            0, 0, 0, 0 ) .setIpad( 0, 0 );
        add( passwordConfirmField, passwordConfirmFieldConstraints );
 
        GBC departmentListConstraints = new GBC( 1, 6, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.WEST ).setFill( GBC.HORIZONTAL ) .setInsets(
            0, 0, 0, 0 ) .setIpad( 0, 0 );
        add( departmentList, departmentListConstraints );
 
        GBC updateUserButtonConstraints = new GBC( 0, 7, 1, 1 ).setWeight( 0, 0 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(
            0, 0, 0, 0 ) .setIpad( 0, 0 );
        add( updateUserButton, updateUserButtonConstraints );
 
        GBC cancelButtonConstraints = new GBC( 1, 7, 1, 1 ).setWeight( 0, 0 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(
            0, 0, 0, 0 ) .setIpad( 0, 0 );
        add( cancelButton, cancelButtonConstraints );
        //@formatter:on
    }
 
    @Override
    public void actionPerformed( ActionEvent e ) {
        if( Arrays.asList( SAVE_PROFILE, UPDATE_PROFILE, CANCEL ).contains( e.getActionCommand() ) ) {
            switch( e.getActionCommand() ) {
                case SAVE_PROFILE:
                    getUserDetails( user );
                    if( !user.isValid() ) {
                        invalidUser();
                        return;
                    }
                    message.onAdd( user );
                    break;
                case UPDATE_PROFILE:
                    getUserDetails( user );
                    if( !user.isValid() ) {
                        invalidUser();
                        return;
                    }
                    message.onUpdate( user );
                    break;
                case CANCEL:
                    cancel();
                    message.onCancel();
                    break;
                default:
                    throw new UnhandledException( "Error Unhandled event [" + e.getSource() + "]" );
            }
        }
    }
 
    public void newUser() {
        UserVO newUser = new UserVO();
        clearForm();
        setState( FORM_ENABLED );
        setMode( MODE_ADD );
        setUser( newUser );
    }
 
    public void setUser( UserVO user ) {
        this.user = user;
    }
 
    public void selectUser( UserVO selectedUser ) {
        clearForm();
        setState( FORM_ENABLED );
        setMode( MODE_UPDATE );
        setUser( selectedUser );
        refreshForm();
    }
 
    public void getUserDetails( UserVO currentUser ) {
        currentUser.firstName = firstNameField.getText();
        currentUser.lastName = lastNameField.getText();
        currentUser.email = emailField.getText();
        currentUser.username = userNameField.getText();
        currentUser.password = Arrays.toString( passwordField.getPassword() );
        currentUser.department = (String) departmentList.getSelectedItem();
    }
 
    public void cancel() {
        clearForm();
        setUser( null );
        setMode( MODE_ADD );
        setState( FORM_DISABLED );
    }
 
    public void refreshForm() {
        firstNameField.setText( user.firstName );
        lastNameField.setText( user.lastName );
        emailField.setText( user.email );
        userNameField.setText( user.username );
        passwordField.setText( user.password );
        passwordConfirmField.setText( user.password );
        departmentList.setSelectedItem( user.department );
    }
 
    public void clearForm() {
        firstNameField.setText( "" );
        lastNameField.setText( "" );
        emailField.setText( "" );
        userNameField.setText( "" );
        passwordField.setText( "" );
        passwordConfirmField.setText( "" );
        departmentList.setSelectedItem( Department.NONE_SELECTED.getValue() );
    }
 
    public void setMode( int mode ) {
        switch( mode ) {
            case MODE_ADD:
                firstNameField.requestFocus();
                updateUserButton.setText( SAVE_PROFILE );
                break;
            case MODE_UPDATE:
                updateUserButton.setText( UPDATE_PROFILE );
                setState( FORM_ENABLED );
                break;
            default:
                break;
        }
    }
 
    public void setState( int state ) {
        boolean enabled = ( state == FORM_ENABLED );
        firstNameField.setEnabled( enabled );
        lastNameField.setEnabled( enabled );
        emailField.setEnabled( enabled );
        userNameField.setEnabled( enabled );
        passwordField.setEnabled( enabled );
        passwordConfirmField.setEnabled( enabled );
        departmentList.setEnabled( enabled );
        updateUserButton.setEnabled( enabled );
        cancelButton.setEnabled( enabled );
    }
 
    public void invalidUser(){
        JOptionPane.showMessageDialog( null, "All fields are required.","Invalid User",JOptionPane.WARNING_MESSAGE );
    }
 
    public void setMessage( UserFormMessage message ) {
        this.message = message;
    }
 
}
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package employeeadmin.view.components;
 
import api.Utils.BorderBuilder;
import api.Utils.GBC;
import api.Utils.UnhandledException;
import employeeadmin.model.enums.Role;
import employeeadmin.model.vo.UserVO;
import employeeadmin.view.interfaces.RolePanelMessage;
 
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Arrays;
import java.util.List;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/3/2015
 */
public class RolePanel extends JPanel implements ActionListener, ListSelectionListener, ItemListener {
 
    public static final int MODE_ADD = 1;
    public static final int MODE_ACTIVE = 2;
    public static final int MODE_UPDATE = 3;
    public static final int FORM_ENABLED = 4;
    public static final int FORM_DISABLED = 5;
 
    private static final String ADD_ROLE = "Add";
    private static final String REMOVE_ROLE = "Remove";
 
    private JList roles;
    private DefaultListModel roleModel;
    private DefaultComboBoxModel roleListModel;
    private JComboBox roleList;
    private JButton addButton;
    private JButton removeButton;
    private List userRoles;
    private UserVO user;
    private Role role;
    private String roleValue;
 
    private RolePanelMessage message;
 
    public RolePanel() {
        setLayout( new GridBagLayout() );
        //@formatter:off
        setBorder(new BorderBuilder( "User Roles", TitledBorder.LEFT, TitledBorder.DEFAULT_POSITION, 2, Font.BOLD, 12 ) );
        //@formatter:on
        initComponents();
    }
 
    private void initComponents() {
 
        roleModel = new DefaultListModel<>();
        roles = new JList<>( roleModel );
        roles.setPreferredSize( new Dimension( 260, 200 ) );
        roles.addListSelectionListener( this );
 
        roleListModel = new DefaultComboBoxModel<>();
        for(Role role : Role.list()) {
            roleListModel.addElement( role.getValue() );
        }
        roleList = new JComboBox<>( roleListModel );
        roleList.addItemListener( this );
 
        addButton = new JButton( ADD_ROLE );
        addButton.addActionListener( this );
 
        removeButton = new JButton( REMOVE_ROLE );
        removeButton.addActionListener( this );
 
        //@formatter:off
        GBC rolesConstraints = new GBC( 0, 0, 3, 1 ).setWeight( 1, 1 ).setAnchor( GBC.NORTH ).setFill( GBC.BOTH ) .setInsets(
            0, 0, 0, 0 ) .setIpad( 0, 0 );
        add( roles, rolesConstraints );
 
        GBC roleListConstraints = new GBC( 0, 1, 1, 1 ).setWeight( 0, 0 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(
            0, 0, 0, 2 ) .setIpad( 0, 0 );
        add( roleList, roleListConstraints );
 
        GBC addButtonConstraints = new GBC( 1, 1, 1, 1 ).setWeight( 0, 0 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(
            0, 0, 0, 2 ) .setIpad( 0, 0 );
        add( addButton, addButtonConstraints );
 
        GBC removeButtonConstraints = new GBC( 2, 1, 1, 1 ).setWeight( 0, 0 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets( 0, 0, 0, 0 ) .setIpad( 0, 0 );
        add( removeButton, removeButtonConstraints );
        //@formatter:on
    }
 
    @Override
    public void actionPerformed( ActionEvent e ) {
 
        if( Arrays.asList( ADD_ROLE, REMOVE_ROLE ).contains( e.getActionCommand() ) ) {
 
            switch( e.getActionCommand() ) {
                case ADD_ROLE:
                    onAdd( user, roleValue );
                    break;
                case REMOVE_ROLE:
                    onRemove( user, roleValue );
                    break;
                default:
                    throw new UnhandledException( "Error Unhandled event [" + e.getSource() + "]" );
            }
        }
    }
 
    private void onRemove( UserVO user, String roleValue ) {
        setUser( user );
        setRole( roleValue );
        message.onRemove( user, role );
    }
 
    private void onAdd( UserVO user, String roleValue ) {
        setUser( user );
        setRole( roleValue );
        message.onAdd( user, role );
    }
 
    @Override
    public void valueChanged( ListSelectionEvent e ) {
        if( !roles.isSelectionEmpty() && !e.getValueIsAdjusting() ) {
            this.roleValue = roles.getSelectedValue();
            setMode( MODE_UPDATE );
        }
    }
 
    @Override
    public void itemStateChanged( ItemEvent e ) {
        if( e.getStateChange() == ItemEvent.SELECTED ) {
            this.roleValue = (String) e.getItem();
            setMode( roleValue.equals( Role.NONE_SELECTED.getValue() ) ? MODE_UPDATE : MODE_ADD );
        }
    }
 
    public void setUser( UserVO selectedUser ) {
        this.user = selectedUser;
    }
 
    public void reloadRoles() {
        for(Role role : userRoles) {
            roleModel.addElement( role.getValue() );
        }
 
    }
 
    public void setRole( String selectedValue ) {
        Role.list().stream().filter( role -> role.getValue().equals( selectedValue ) ).forEach( role -> {
            this.role = role;
        } );
 
    }
 
    public void setMode( int mode ) {
 
        switch( mode ) {
            case MODE_ADD:
                roles.getSelectionModel().clearSelection();
                roleList.setEnabled( true );
                addButton.setEnabled( true );
                removeButton.setEnabled( false );
                break;
            case MODE_ACTIVE:
                roles.getSelectionModel().clearSelection();
                roleListModel.setSelectedItem( Role.NONE_SELECTED.getValue() );
                roleList.setEnabled( true );
                addButton.setEnabled( false );
                removeButton.setEnabled( false );
                break;
            case MODE_UPDATE:
                roleList.setEnabled( true );
                addButton.setEnabled( false );
                removeButton.setEnabled( true );
                break;
            default:
                break;
        }
 
    }
 
    public void setState( int state ) {
 
        boolean enabled = ( state == FORM_ENABLED );
        roles.setEnabled( enabled );
        roleList.setEnabled( enabled );
        addButton.setEnabled( enabled );
        removeButton.setEnabled( enabled );
 
    }
 
    public void setMessage( RolePanelMessage message ) {
        this.message = message;
    }
 
    public void refreshPanel() {
        roleModel.clear();
    }
 
    public void setRoles( List userRoles ) {
        this.userRoles = userRoles;
    }
 
    public UserVO getUser() {
        return user;
    }
 
    public void selectUser( UserVO user ) {
        refreshPanel();
        setState( RolePanel.FORM_ENABLED );
        setUser( user );
        setMode( MODE_ACTIVE );
        reloadRoles();
    }
 
    public void cancel() {
        refreshPanel();
        setState( RolePanel.FORM_DISABLED );
    }
}

Адаптер обмена сообщениями

Как объяснялось, каждый компонент содержит экземпляр своего интерфейса адаптера, который позволяет компоненту отправлять сообщения своему посреднику. Затем посредник передает сообщение произвольному списку заинтересованных наблюдателей.

Приведенная ниже диаграмма объектов иллюстрирует UserList коллабораторов UserList в приложении. Обратите внимание, как UserListMediator действует как Mediator/Controller и направляет сообщения в UserList через интерфейс адаптера UserListMessage .

ява-свинг-MVA-пользователь

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
package employeeadmin.view.interfaces;
 
import employeeadmin.model.vo.UserVO;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/8/15
 */
public interface UserListMessage {
 
    void onNew();
 
    void onSelect( UserVO user );
 
    void onDelete( UserVO user );
 
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
package employeeadmin.view.interfaces;
 
import employeeadmin.model.vo.UserVO;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/8/2015
 */
public interface UserFormMessage {
 
    void onAdd( UserVO user );
 
    void onUpdate( UserVO user );
 
    void onCancel();
 
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
package employeeadmin.view.interfaces;
 
import employeeadmin.model.enums.Role;
import employeeadmin.model.vo.UserVO;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/8/2015
 */
public interface RolePanelMessage {
 
    void onAdd( UserVO user, Role role );
 
    void onRemove( UserVO user, Role role );
}

Медиатор Контроллер

Каждый mediator выступает в качестве mediating controller , обрабатывает регистрацию своего компонента представления, регистрирует события приложения, о которых необходимо уведомить, и обрабатывает реализацию уведомления.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package employeeadmin.view;
 
import employeeadmin.ApplicationFacade;
import employeeadmin.model.UserProxy;
import employeeadmin.model.vo.UserVO;
import employeeadmin.view.components.UserList;
import employeeadmin.view.interfaces.UserListMessage;
import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.mediator.Mediator;
 
import java.util.ArrayList;
 
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/4/2015
 */
public class UserListMediator extends Mediator implements UserListMessage {
 
    public static final String NAME = "UserListMediator";
 
    private UserProxy userProxy;
 
    public UserListMediator( UserList viewComponent ) {
        super( NAME, viewComponent );
    }
 
    @Override
    public void onRegister() {
        getUserList().setMessage( this );
    }
 
    public String[] listNotificationInterests() {
        return new String[]{
            ApplicationFacade.INIT_USERS,
            ApplicationFacade.USER_ADDED,
            ApplicationFacade.USER_UPDATED,
            ApplicationFacade.USER_DELETED,
            ApplicationFacade.USER_SELECTED,
            ApplicationFacade.CANCEL_SELECTED
        };
    }
 
    @Override
    public void handleNotification( final INotification note ) {
        userProxy = (UserProxy) getFacade().retrieveProxy( "UserProxy" );
        final ArrayList users = userProxy.getUsers();
        switch( note.getName() ) {
            case ApplicationFacade.INIT_USERS:
                getUserList().reloadUsers( users );
                break;
            case ApplicationFacade.USER_ADDED:
                getUserList().reloadUsers( users );
                getUserList().addUser( (UserVO) note.getBody() );
                break;
            case ApplicationFacade.USER_UPDATED:
                getUserList().reloadUsers( users );
                break;
            case ApplicationFacade.USER_SELECTED:
                getUserList().setUser( userProxy.getUser( (UserVO) note.getBody() ) );
                break;
            case ApplicationFacade.CANCEL_SELECTED:
                getUserList().cancelSelection();
                break;
            case ApplicationFacade.USER_DELETED:
                getUserList().reloadUsers( users );
                getUserList().cancelSelection();
                break;
        }
    }
 
    @Override
    public void onNew() {
        sendNotification( ApplicationFacade.NEW_USER );
    }
 
    @Override
    public void onSelect( UserVO user ) {
        sendNotification( ApplicationFacade.USER_SELECTED, user );
    }
 
    @Override
    public void onDelete( UserVO user ) {
        sendNotification( ApplicationFacade.DELETE_USER, user );
    }
 
    private UserList getUserList() {
        return (UserList) viewComponent;
    }
 
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package employeeadmin.view;
 
import employeeadmin.ApplicationFacade;
import employeeadmin.model.vo.UserVO;
import employeeadmin.view.components.UserForm;
import employeeadmin.view.interfaces.UserFormMessage;
import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.mediator.Mediator;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/5/2015
 */
public class UserFormMediator extends Mediator implements UserFormMessage {
 
    public static String NAME = "UserFormMediator";
 
    public UserFormMediator( UserForm viewComponent ) {
        super( NAME, viewComponent );
        setViewComponent( viewComponent );
    }
 
    public String[] listNotificationInterests() {
        return new String[]{
            ApplicationFacade.NEW_USER,
            ApplicationFacade.USER_SELECTED,
            ApplicationFacade.USER_DELETED
        };
    }
 
    @Override
    public void onRegister() {
        getUserForm().setMessage( this );
        getUserForm().setMode( UserForm.MODE_ADD );
        getUserForm().setState( UserForm.FORM_DISABLED );
    }
 
    @Override
    public void handleNotification( INotification note ) {
 
        switch( note.getName() ) {
 
            case ApplicationFacade.NEW_USER:
                getUserForm().newUser();
                break;
            case ApplicationFacade.USER_SELECTED:
                getUserForm().selectUser( (UserVO) note.getBody() );
                break;
            case ApplicationFacade.USER_DELETED:
                getUserForm().setState( UserForm.FORM_DISABLED );
                getUserForm().clearForm();
                break;
        }
    }
 
    @Override
    public void onAdd( UserVO user ) {
        sendNotification( ApplicationFacade.USER_ADDED, user );
    }
 
    @Override
    public void onUpdate( UserVO user ) {
        sendNotification( ApplicationFacade.USER_UPDATED, user );
    }
 
    @Override
    public void onCancel() {
        sendNotification( ApplicationFacade.CANCEL_SELECTED );
    }
 
    private UserForm getUserForm() {
        return (UserForm) viewComponent;
    }
}
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
package employeeadmin.view;
 
import employeeadmin.ApplicationFacade;
import employeeadmin.model.RoleProxy;
import employeeadmin.model.enums.Role;
import employeeadmin.model.vo.RoleVO;
import employeeadmin.model.vo.UserVO;
import employeeadmin.view.components.RolePanel;
import employeeadmin.view.interfaces.RolePanelMessage;
import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.mediator.Mediator;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/5/2015
 */
public class RolePanelMediator extends Mediator implements RolePanelMessage {
 
    public static String NAME = "RolePanelMediator";
 
    private RoleProxy roleProxy;
 
    public RolePanelMediator( RolePanel viewComponent ) {
        super( NAME, viewComponent );
        setViewComponent( viewComponent );
    }
 
    @Override
    public void onRegister() {
        getRolePanel().setMessage( this );
        getRolePanel().setState( RolePanel.FORM_DISABLED );
    }
 
    @Override
    public String[] listNotificationInterests() {
        return new String[]{
            ApplicationFacade.NEW_USER,
            ApplicationFacade.USER_ADDED,
            ApplicationFacade.USER_UPDATED,
            ApplicationFacade.USER_DELETED,
            ApplicationFacade.CANCEL_SELECTED,
            ApplicationFacade.USER_SELECTED,
            ApplicationFacade.ADD_ROLE_RESULT
        };
    }
 
    public void handleNotification( INotification note ) {
        roleProxy = (RoleProxy) getFacade().retrieveProxy( "RoleProxy" );
        switch( note.getName() ) {
            case ApplicationFacade.NEW_USER:
                break;
            case ApplicationFacade.USER_ADDED:
                getRolePanel().setUser( (UserVO) note.getBody() );
                roleProxy.addRole( new RoleVO( ( (UserVO) note.getBody() ).username, new ArrayList<>() ) );
                break;
            case ApplicationFacade.USER_UPDATED:
                break;
            case ApplicationFacade.USER_DELETED:
                break;
            case ApplicationFacade.CANCEL_SELECTED:
                getRolePanel().cancel();
                break;
            case ApplicationFacade.USER_SELECTED:
                List roles = roleProxy.getUserRoles( ( (UserVO) note.getBody() ).username );
                getRolePanel().setRoles( roles );
                getRolePanel().selectUser( (UserVO) note.getBody() );
                break;
            case ApplicationFacade.ADD_ROLE_RESULT:
                break;
            default:
                break;
        }
    }
 
    @Override
    public void onAdd( UserVO user, Role role ) {
        List roles = roleProxy.getUserRoles( user.username );
        roleProxy.addRoleToUser( user, role );
        getRolePanel().refreshPanel();
        getRolePanel().reloadRoles();
        sendNotification( ApplicationFacade.ADD_ROLE, user );
    }
 
    @Override
    public void onRemove( UserVO user, Role role ) {
        roleProxy.removeRoleFromUser( user, role );
 
        getRolePanel().refreshPanel();
        getRolePanel().reloadRoles();
 
        sendNotification( ApplicationFacade.USER_UPDATED, user );
    }
 
    public RolePanel getRolePanel() {
        return (RolePanel) viewComponent;
    }
 
}

Слой модели

Слой модели для этого приложения состоит из двух перечислений, двух объектов-значений и двух прокси-объектов. Объекты значений используются в компонентах представления для поддержки разделения интересов путем делегирования доступа уровня модели к прокси-объектам — они создают дублирующийся код, но служат хорошей цели. Прокси-объекты несут основную ответственность за весь доступ к данным.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package employeeadmin.model.enums;
 
import org.apache.commons.lang3.builder.ToStringBuilder;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/9/2015
 */
public enum Department {
 
    NONE_SELECTED( "--None Selected--", -1 ),
    ACCT( "Accounting", 0 ),
    SALES( "Sales", 1 ),
    PLANT( "Plant", 2 ),
    SHIPPING( "Shipping", 3 ),
    QC( "Quality Control", 4 );
 
    private final String value;
    private final Integer ordinal;
 
    Department( String value, Integer ordinal ) {
        this.value = value;
        this.ordinal = ordinal;
    }
 
    public static List list() {
        ArrayList list = new ArrayList<>();
        list.add( NONE_SELECTED );
        list.add( ACCT );
        list.add( SALES );
        list.add( PLANT );
        return list;
    }
 
    public String getValue() {
        return value;
    }
 
    public Integer getOrdinal() {
        return ordinal;
    }
 
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString( this );
    }
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package employeeadmin.model.enums;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/9/2015
 */
public enum Role {
 
    /**
     * Roles.
     */
    NONE_SELECTED( "--None Selected--", -1 ),
    ADMIN( "Administrator", 0 ),
    ACCT_PAY( "Accounts Payable", 1 ),
    ACCT_RCV( "Accounts Receivable", 2 ),
    EMP_BENEFITS( "Employee Benefits", 3 ),
    GEN_LEDGER( "General Ledge", 4 ),
    PAYROLL( "Payroll", 5 ),
    INVENTORY( "Inventory", 6 ),
    PRODUCTION( "Production", 7 ),
    QUALITY_CTL( "Quality Control", 8 ),
    SALES( "Sales", 9 ),
    ORDERS( "Orders", 10 ),
    CUSTOMERS( "Customers", 11 ),
    SHIPPING( "Shipping", 12 ),
    RETURNS( "Returns", 13 );
 
    private final Integer ordinal;
    private final String value;
 
    Role( String value, Integer ordinal ) {
        this.value = value;
        this.ordinal = ordinal;
    }
 
    public static List list() {
        ArrayList list = new ArrayList<>();
        list.add( NONE_SELECTED );
        list.add( ADMIN );
        list.add( ACCT_PAY );
        list.add( ACCT_RCV );
        list.add( EMP_BENEFITS );
        list.add( GEN_LEDGER );
        list.add( PAYROLL );
        list.add( INVENTORY );
        list.add( PRODUCTION );
        list.add( QUALITY_CTL );
        list.add( SALES );
        list.add( ORDERS );
        list.add( CUSTOMERS );
        list.add( SHIPPING );
        list.add( RETURNS );
 
        return list;
    }
 
    public Integer getOrdinal() {
        return ordinal;
    }
 
    public String getValue() {
        return value;
    }
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package employeeadmin.model.vo;
 
import employeeadmin.model.enums.Department;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
 
import java.io.Serializable;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/2/2015
 */
public class UserVO implements Serializable {
 
    public static final long serialVersionUID = 1L;
 
    public String username;
    public String firstName;
    public String lastName;
    public String email;
    public String password;
    public String department;
 
    public UserVO() {
    }
 
    public UserVO( final String userName, final String firstName, final String lastName, final String email,
        final String password, final String department ) {
        this.username = userName;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.password = password;
        this.department = department != null ? department : Department.NONE_SELECTED.getValue();
 
    }
 
    public final boolean isValid() {
        return
            ( !"".equals( username ) ) &&
            ( !"".equals( firstName ) ) &&
            ( !"".equals( lastName ) ) &&
            ( !"".equals( email ) ) &&
            ( !"".equals( password ) ) &&
            ( !Department.NONE_SELECTED.getValue().equals( department ) );
    }
 
    @Override
    public boolean equals( Object o ) {
        if( this == o ) { return true; }
 
        if( !( o instanceof UserVO ) ) { return false; }
 
        UserVO userVO = (UserVO) o;
 
        return new EqualsBuilder()
            .append( username, userVO.username )
            .append( firstName, userVO.firstName )
            .append( lastName, userVO.lastName )
            .append( email, userVO.email )
            .append( password, userVO.password )
            .append( department, userVO.department )
            .isEquals();
    }
 
    @Override
    public int hashCode() {
        return new HashCodeBuilder( 17, 37 )
            .append( username )
            .append( firstName )
            .append( lastName )
            .append( email )
            .append( password )
            .append( department )
            .toHashCode();
    }
 
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString( this, ToStringStyle.JSON_STYLE );
    }
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package employeeadmin.model.vo;
 
import employeeadmin.model.enums.Role;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
 
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/2/2015
 */
public class RoleVO implements Serializable {
 
    public static final long serialVersionUID = 1L;
 
    public String username;
    public List roles = new ArrayList<>();
 
    public RoleVO( final String username, final List roles ) {
        if( username != null ) {
            this.username = username;
        }
        if( roles != null ) {
            this.roles = new ArrayList<>( roles );
        }
    }
 
    @Override
    public boolean equals( Object o ) {
        if( this == o ) { return true; }
 
        if( !( o instanceof RoleVO ) ) { return false; }
 
        RoleVO roleVO = (RoleVO) o;
 
        return new EqualsBuilder()
            .append( username, roleVO.username )
            .append( roles, roleVO.roles )
            .isEquals();
    }
 
    @Override
    public int hashCode() {
        return new HashCodeBuilder( 17, 37 )
            .append( username )
            .append( roles )
            .toHashCode();
    }
 
    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString( this, ToStringStyle.JSON_STYLE );
    }
}
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package employeeadmin.model;
 
import employeeadmin.model.vo.UserVO;
import org.puremvc.java.multicore.patterns.proxy.Proxy;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/2/2015
 */
public class UserProxy extends Proxy {
 
    public static final String NAME = "UserProxy";
 
    public static List USERS = new ArrayList<>();
 
    public UserProxy() {
        super( NAME, USERS );
    }
 
    @SuppressWarnings( "unchecked" )
    public final ArrayList getUsers() {
        return (ArrayList) this.getData();
    }
 
    public final UserVO getUser( UserVO userVO ) {
        for(UserVO user : getUsers()) {
            if( userVO == user ) {
                return user;
            }
        }
 
 
        return null;
    }
 
    public final void addUser( final UserVO user ) {
        getUsers().add( user );
    }
 
    public final void updateUser( final UserVO user ) {
        for(int i = 0; i < getUsers().size(); i++) {
            if( getUsers().get( i ).username.equals( user.username ) ) {
                getUsers().set( i, user );
            }
        }
    }
 
    public final void deleteUser( final UserVO user ) {
        if( getUsers().contains( user ) ) {
            getUsers().remove( user );
        }
    }
}
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
package employeeadmin.model;
 
import employeeadmin.model.enums.Role;
import employeeadmin.model.vo.RoleVO;
import employeeadmin.model.vo.UserVO;
import org.puremvc.java.multicore.patterns.proxy.Proxy;
 
import java.util.ArrayList;
import java.util.List;
 
import static employeeadmin.ApplicationFacade.ADD_ROLE_RESULT;
 
/**
 * @author Edward Beckett :: <Edward@EdwardBeckett.com>
 * @since :: 6/2/2015
 */
public class RoleProxy extends Proxy {
 
    public static final String NAME = "RoleProxy";
 
    private static final List ROLES = new ArrayList<>();
 
    public RoleProxy() {
        super( NAME, ROLES );
    }
 
    @SuppressWarnings( "unchecked" )
    public final List getRoles() {
        return (List) this.getData();
    }
 
    public final void addRole( final RoleVO role ) {
        getRoles().add( role );
    }
 
    public final void deleteRole( final UserVO user ) {
        for(int i = 0; i < getRoles().size(); i++) {
            if( getRoles().get( i ).username.equals( user.username ) ) {
                getRoles().remove( i );
            }
        }
    }
 
    public final boolean userHasRole( final UserVO user, final Role role ) {
        boolean hasRole = false;
        for(int i = 0; i < getRoles().size(); i++) {
            if( getRoles().get( i ).username.equals( user.username ) ) {
                List userRoles = getRoles().get( i ).roles;
                for(Role userRole : userRoles) {
                    if( role.equals( userRole ) ) {
                        hasRole = true;
                        break;
                    }
                }
                break;
            }
        }
        return hasRole;
    }
 
    public final void addRoleToUser( final UserVO user, final Role role ) {
        boolean result = false;
        if( !userHasRole( user, role ) ) {
            for(int i = 0; i < getRoles().size(); i++) {
                if( getRoles().get( i ).username.equals( user.username ) ) {
                    List userRoles = getRoles().get( i ).roles;
                    userRoles.add( role );
                    result = true;
                    break;
                }
            }
        }
        sendNotification( ADD_ROLE_RESULT, result );
    }
 
    public final void removeRoleFromUser( final UserVO user, final Role role ) {
        if( userHasRole( user, role ) ) {
            for(int i = 0; i < getRoles().size(); i++) {
                if( getRoles().get( i ).username.equals( user.username ) ) {
                    List userRoles = getRoles().get( i ).roles;
                    for(int j = 0; j < userRoles.size(); j++) {
                        if( userRoles.get( j ).equals( role ) ) {
                            userRoles.remove( j );
                            break;
                        }
                    }
                    break;
                }
            }
        }
    }
 
    public final List getUserRoles( final String username ) {
        List userRoles = new ArrayList<>();
        for(int i = 0; i < getRoles().size(); i++) {
            if( getRoles().get( i ).username.equals( username ) ) {
                userRoles = getRoles().get( i ).roles;
                break;
            }
        }
        return userRoles;
    }
 
}
Ссылка: Java Swing Model View Adapter Mediator from our JCG partner Edward Beckett at the Design Develop Deliver blog.