الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

مثال على MVC Pattern ، ، ،

مغلق
بدأه زائر في 6 أكتوبر 2006 · 3 رد · 1,642 مشاهدة · في JavaEE
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

السـلام عليكم

اخواني هذا مثال على mvc وأريده أن يحقق أفضل شكل لهذا الpattern

4345345234.JPG

اتمنى ان ارى ملاحظاتكم

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Vector;
import javax.swing.*; 
import javax.swing.border.Border;

/*		   
 *				Three Classes : 
 *				Controller : The logic That glues specification together .
 *
 *				View	   : Used for Presentation in events View gets 
 *				   message to The model which does the data maintenance .
 *  
 *				Model	  : Storage not presentation it is response 
 *				   for isolated data operations ( add , update , search ).
 *
 *
 *			 /////////////////////////////////////////////////////
 *			   
 *				MVC advantage applied in this example because 
 *				The GUI interface ( View ) doesn't know any thing	
 *				about How to addEntry or how extract The searchResult(Model)
 *		 
 *			///////////////////////////////////////////////////////
 *
 *		   
 */ 

// <-------------------- Controller Class --------------------------------->
	// Interpreter Between Data Maintenance (model) and Presentation (view) 
public class Controller{ 
	private Model model;
	private View view;

	public Controller()
	{
		view = new View(this);
		model = new Model(view);
	}
	public void  start()
	{
	 model.setState("idle");   
	}
	public static void main(String args[])
	{
		Controller controller=new Controller();
		controller.start();
	}
}

//<------------------------------ View Class --------------------->
	   // Presentation Here How To Display (Add) form , (Search) form 
class View {
   private final Controller controller;
   private   Model model; 
   private  JTextField nameField,numberField;
   private  JFrame frame,frame3,frame2;
   private  JButton add,search,quit;
   private  JLabel exit;

	public View(Controller m)
	{
		controller=m;

	}
	public void stateHasChanged(Model m,String stat)
	{
		model =m;
		changeView(stat);

	}

	public void changeView(String stat) {
		 if(stat.equals("add"))
			 add();
		 else
			 if(stat.equals("search"))
				 search();
			 else
				 if(stat.equals("quit"))
					 quit();
				 else
					 form();

	}
	public void form()
	{
			   frame=new JFrame("TelphoneDirectory . . "); 
			   JPanel panel = new JPanel();
			   panel.setBackground(Color.YELLOW);
			   add=new JButton("add ");
			   search=new JButton("search");
			   quit=new JButton(" quit "); 
			   panel.add(add);
			   panel.add(search);
			   panel.add(quit);

			   add.setFont(new Font("Rimes New Roman",Font.BOLD,20));
			   search.setFont(new Font("Rimes New Roman",Font.BOLD,20));
			   quit.setFont(new Font("Rimes New Roman",Font.BOLD,20));


			   JLabel intro=new JLabel("Please Choose an Operation ,,");  
			   Font font=new Font("Times New Roman", Font.ITALIC, 20);
			   intro.setFont(font);
			   frame.add(panel);
			   frame.add(intro);
			   ImageIcon icon = new ImageIcon("c:/pic1.gif");
			   JLabel temp=new JLabel(icon);
			   frame.add(temp);
			   ImageIcon ico=new ImageIcon("c:/home.gif");
			   temp=new JLabel(ico);
			   frame.add(temp);

			   add.addActionListener(new ActionListener() {
				   public void actionPerformed(ActionEvent e) {
				model.setState("add");

				   }
			   });
			  search.addActionListener(new ActionListener() {
				   public void actionPerformed(ActionEvent e) {
				  model.setState("search");
				   }
			   });
			   quit.addActionListener(new ActionListener() {
				   public void actionPerformed(ActionEvent e) {
				  model.setState("quit");
				   }
			   });
			   frame.setSize(400,340);
			   frame.setLayout(new FlowLayout()); 
			   frame.setVisible(true);

	}
   public void add()
   {
	  frame2=new JFrame("ADD ");
	  JPanel panel=new JPanel();
	  JPanel panel2=new JPanel();
	  JLabel name=new JLabel("Name");
	  JLabel number=new JLabel("Number");
	  JButton save=new JButton("save"); 
	  Font font = new Font("Times New Roman",Font.BOLD,30);
	  save.setFont(font);
	  nameField=new JTextField("",20); 
	  numberField=new JTextField("",20);
	  panel.add(name); 
	  panel.add(nameField);
	  panel2.add(number);
	  panel2.add(numberField); 
	  frame2.add(panel);
	  frame2.add(panel2);
	  frame2.add(save);
	  frame2.setLayout(new FlowLayout());
		frame2.setDefaultCloseOperation(2);
		frame2.setSize(300,300);
		frame2.setVisible(true);   

		save.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
		   model.addAnEntry(nameField.getText(),numberField.getText());
					  frame2.setVisible(false);
			}
		});

   }
   public void search()
   {  
	   frame3=new JFrame("Search");
	   nameField=new JTextField("",20);
	   JButton search=new JButton("Search");
	   frame3.add(nameField);
	   frame3.add(search);
			ImageIcon icon = new ImageIcon("c:/mslogo.gif");
			JLabel label=new JLabel(icon);
			frame3.add(label);
		  search.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

	   String target="PhoneNumber:  "+ model.searchPhoneNumber(nameField.getText());
				exit.setText(target);
				ImageIcon icon = new ImageIcon("c:/phone.gif");
				exit.setIcon(icon); 
				frame3.add(exit);
				frame3.validate();

			}

		});
		exit=new JLabel("");
		frame3.setLayout(new FlowLayout());
		frame3.setDefaultCloseOperation(2);
		frame3.setSize(300,300);
		frame3.setVisible(true);  
   }
   public void quit()
   {  
	   model.saveAll();
		exit=new JLabel(" bye bye");
		Font font = new Font("Times New Roman ",Font.ITALIC,20);
		exit.setFont(font);
		ImageIcon icon = new ImageIcon("c:/jfc.gif");
		JLabel temp=new JLabel(icon);
		add.setEnabled(false);
		search.setEnabled(false);
		quit.setEnabled(false);
		frame.add(exit);
		frame.add(temp); 
		frame.setDefaultCloseOperation(2);   // Exit By X 
		frame.validate();   // Appear The Changes 
   }

}
//<---------------------- Model Class ----------------------------------->
		//   Data Maintenance  how To (Add ) Data , how To (Search ) Data 

class Model {
  private final  View view;
  private  Vector vector;
  private  String state;
	File file;
	public Model(View v)
	{
	 view=v;   
	 vector = new Vector();

	}
	public void setState(String stat)
	{
		state=stat;
		view.stateHasChanged(this,state);
	}

	public void addAnEntry(String name,String number)
	{
		vector.add(name);
		vector.add(number);
	}

	public String searchPhoneNumber(String name)
	{  String target="Not Found ";
		boolean flag=true;
		 file=new File("TelephoneDirectory.txt");
			try{
				RandomAccessFile raf=new RandomAccessFile(file,"rw");
				raf.seek(0);
				while(raf.getFilePointer()!=raf.length()&& flag)
				{
					if(raf.readUTF().equalsIgnoreCase(name))
					{
						target=raf.readUTF();
						flag=false;	
					}
				}
			}
			catch(IOException ee)
			{
				System.out.println("There is a problem Occured in The File ");
			}

			if(flag)
			{
			   int counter=0;
			   boolean flag2=true;
			   while(counter<vector.size()-1&& flag2)
			   {
				   String targett=(String)vector.get(counter);
				   if(targett.equalsIgnoreCase(name))
				   {
					   target=(String) vector.get(counter);
					   flag2=false;
				   }
				   else
					   counter++;
			   }

				if(!flag2)
					target=(String)vector.get(++counter);
			}  

		return target;
	}

	public void saveAll()
	{
		try{
			 file = new File("TelephoneDirectory.txt");
			 RandomAccessFile raf=new RandomAccessFile(file,"rw");
			 raf.seek(raf.length());
			 for(int iterator=0;iterator<vector.size();iterator++)
			   raf.writeUTF((String) vector.get(iterator));
	  }
	  catch(IOException ee)
	  {
		  System.out.println("There is A problem with this File "+file);
	  }

	}

}
#2

السلام عليكم،،

ما شاء الله مثال جميل وسهل ومبسط..

إليك بعض الملاظات

1- تسمية الفئات بأسماء مفيدة يسهل علينا طريقة التواصل،، من الملاحظ أنك استخدمت أسماء جميلة،، لكننا طماعون!

مثلا،، Model اسم جميل،، ولكن PhoneModel أحلى!

2- إذا أردت أن تعرف أن تصميمك ممتاز،، فإن الـ View يجب ألا يتحدث مع الـ Model.. وكذلك الModel يجب ألا يتحدث مع View.

ال Controller هو المسؤول عن التواصل.

لاحظ الشفرة التالية،، لاحظ أني طورت تصميم البرنامج ولم أطور التفاصيل... مثلا لم أعدل Vector في PhoneModel وكان من الأفضل استخدام Map.

package test;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.Border;

/*		  
*				Three Classes :
*				Controller : The logic That glues specification together .
*
*				View	   : Used for Presentation in events View gets
*				   message to The model which does the data maintenance .
*  
*				Model	  : Storage not presentation it is response
*				   for isolated data operations ( add , update , search ).
*
*
*			 /////////////////////////////////////////////////////
*			  
*				MVC advantage applied in this example because
*				The GUI interface ( View ) doesn't know any thing	
*				about How to addEntry or how extract The searchResult(Model)
*		
*			///////////////////////////////////////////////////////
*
*		  
*/

// <-------------------- Controller Class --------------------------------->
	// Interpreter Between Data Maintenance (model) and Presentation (view)
public class Controller{//What is this class supposed to do??
//This class is supposed to CONTROL things if not everything!
	private PhoneModel model;
	private View view;

	public Controller()
	{
		view = new View();
		model = new PhoneModel();
		init();
	}
	private void init(){
		view.addSaveActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ar){
				model.addAnEntry(view.getEnteredName(), view.getEnterredNumber());
				view.showMessage("Confirmation", "Record Added");
			}
		});
		view.addSearchActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ar){
				String answer=model.searchPhoneNumber(view.getSearchName());
				view.showMessage("Search Result", answer);
			}
		});
	}
	public void  start()
	{
	 view.start();
	}
	public static void main(String args[])
	{
		Controller controller=new Controller();
		controller.start();
	}
}

//<------------------------------ View Class --------------------->
	   // Presentation Here How To Display (Add) form , (Search) form
class View {//You should call the view with a better name.
//   private final Controller controller;
//   private   Model model; //You should not reference any Model here!!
   private  JTextField searchNameField, nameField,numberField;
   private  JFrame motherFrame,addFrame,searchFrame;
   private  JButton addButton,searchButton,quitButton;
   private  JLabel exit;

	public View()
	{
	  init();//prepare Views  

	}
	public void showMessage(String type, String message){
		JOptionPane.showMessageDialog(motherFrame,message, type, JOptionPane.INFORMATION_MESSAGE);
	}
	private void init(){
		prepareAddFrame();
		prepareSearchFrame();
		prepareMotherFrame();
	}
	public String getSearchName(){
		return searchNameField.getText();
	}
	public String getEnteredName(){
		return nameField.getText();
	}
	public String getEnterredNumber(){
		return numberField.getText();
	}
	public void start(){
		motherFrame.setVisible(true);
	}
	public void addSaveActionListener(ActionListener listener){
		addButton.addActionListener(listener);
	}
	public void addSearchActionListener(ActionListener listener){
		searchButton.addActionListener(listener);

	}
	public void addQuitActionListener(ActionListener listener){
		quitButton.addActionListener(listener);
	}
	public void stateHasChanged(String stat)
	{
		changeView(stat);

	}

	public void changeView(String stat) {
		 if(stat.equals("add"))
			 addFrame.setVisible(true);
		 else
			 if(stat.equals("search"))
				 searchFrame.setVisible(true);
			 else
				 if(stat.equals("quit"))
					 quit();
				 else
					 motherFrame.setVisible(true);

	}
	public void prepareMotherFrame()	{
			   JFrame frame=new JFrame("TelphoneDirectory . . ");
			   frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
			   final JLabel label=new JLabel();
			   JPanel panel = new JPanel();
			   panel.setBackground(Color.YELLOW);
			   final JButton add=new JButton(new AbstractAction("Add"){
				   public void actionPerformed(ActionEvent a){
					   addFrame.setVisible(true);
				   }
			   });
			   final JButton search=new JButton(new AbstractAction("Search"){
				   public void actionPerformed(ActionEvent a){
					   searchFrame.setVisible(true);
				   }
			   });
			   final JButton quit=new JButton();
			   quit.setAction(new AbstractAction("Quit"){
				   public void actionPerformed(ActionEvent a){
					   add.setEnabled(false);
					  search.setEnabled(false);
					quit.setEnabled(false);
					label.setText("Fee Aman Allah");
				   }
			   });
			   panel.add(add);
			   panel.add(search);
			   panel.add(quit);
				  panel.add(label);
			   add.setFont(new Font("Rimes New Roman",Font.BOLD,20));
			   search.setFont(new Font("Rimes New Roman",Font.BOLD,20));
			   quit.setFont(new Font("Rimes New Roman",Font.BOLD,20));


			   JLabel intro=new JLabel("Please Choose an Operation ,,");  
			   Font font=new Font("Times New Roman", Font.ITALIC, 20);
			   intro.setFont(font);
			   frame.add(panel);
			   frame.add(intro);
			   ImageIcon icon = new ImageIcon("c:/pic1.gif");
			   JLabel temp=new JLabel(icon);
			   frame.add(temp);
			   ImageIcon ico=new ImageIcon("c:/home.gif");
			   temp=new JLabel(ico);
			   frame.add(temp);

			   frame.setSize(400,340);
			   frame.setLayout(new FlowLayout());

			   motherFrame=frame;
			   //frame.setVisible(true);

	}
   public void prepareAddFrame()
   {
	  final JFrame frame2=new JFrame("ADD ");
	  JPanel panel=new JPanel();
	  JPanel panel2=new JPanel();
	  JLabel name=new JLabel("Name");
	  JLabel number=new JLabel("Number");
	  addButton=new JButton("save");
	  Font font = new Font("Times New Roman",Font.BOLD,30);
	  addButton.setFont(font);
	  nameField=new JTextField("",20);
	  numberField=new JTextField("",20);
	  panel.add(name);
	  panel.add(nameField);
	  panel2.add(number);
	  panel2.add(numberField);
	  frame2.add(panel);
	  frame2.add(panel2);
	  frame2.add(addButton);
	  frame2.setLayout(new FlowLayout());
		frame2.setDefaultCloseOperation(2);
		frame2.setSize(300,300);
	   // frame2.setVisible(true);  

		addButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
					  frame2.setVisible(false);
			}
		});
	  addFrame=frame2;
   }
   public void prepareSearchFrame()
   {  
	   JFrame frame3=new JFrame("Search");
	   searchNameField=new JTextField("",20);
	   searchButton=new JButton("Search");
	   frame3.add(searchNameField);
	   frame3.add(searchButton);
			ImageIcon icon = new ImageIcon("c:/mslogo.gif");
			JLabel label=new JLabel(icon);
			frame3.add(label);
		  searchButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
		 /*	  
	   String target="PhoneNumber:  "+ model.searchPhoneNumber(nameField.getText());
				exit.setText(target);
				ImageIcon icon = new ImageIcon("c:/phone.gif");
				exit.setIcon(icon);
				frame3.add(exit);
				frame3.validate();
		   */ 
			}

		});
		exit=new JLabel("");
		frame3.setLayout(new FlowLayout());
		frame3.setDefaultCloseOperation(2);
		frame3.setSize(300,300);
	   // frame3.setVisible(true);  
	   searchFrame=frame3;
   }
   public void quit()
   {  
	//   model.saveAll();
		exit=new JLabel("fee 7fth Allah");
		Font font = new Font("Times New Roman",Font.ITALIC,20);
		exit.setFont(font);
		ImageIcon icon = new ImageIcon("c:/jfc.gif");
		JLabel temp=new JLabel(icon);
		JFrame frame=motherFrame;
		frame.add(exit);
		frame.add(temp);
		frame.setDefaultCloseOperation(2);   // Exit By X
		frame.validate();   // Appear The Changes
   }

}
//<---------------------- Model Class ----------------------------------->
		//   Data Maintenance  how To (Add ) Data , how To (Search ) Data

class PhoneModel {//Give the class a better name!!
//  private final  View view;
  private  Vector vector;//You should have used a Map instead of a Vector
  //give the vector variable a better name.
	File file;
	public PhoneModel()
	{
	 vector = new Vector();
	//You should read from the File here!
	}
	public java.util.List getAllNumbers(){
		return new ArrayList(vector);
	}


	public void addAnEntry(String name,String number)
	{
		//You should have used a map.
		vector.add(name);
		vector.add(number);
	}

	public String searchPhoneNumber(String name)
	{  String target="Not Found ";
		boolean flag=true;
		 file=new File("TelephoneDirectory.txt");
			try{
				RandomAccessFile raf=new RandomAccessFile(file,"rw");
				raf.seek(0);
				while(raf.getFilePointer()!=raf.length()&& flag)
				{
					if(raf.readUTF().equalsIgnoreCase(name))
					{
						target=raf.readUTF();
						flag=false;	
					}
				}
			}
			catch(IOException ee)
			{
				System.out.println("There is a problem Occured in The File ");
			}

			if(flag)
			{
			   int counter=0;
			   boolean flag2=true;
			   while(counter<vector.size()-1&& flag2)
			   {
				   String targett=(String)vector.get(counter);
				   if(targett.equalsIgnoreCase(name))
				   {
					   target=(String) vector.get(counter);
					   flag2=false;
				   }
				   else
					   counter++;
			   }

				if(!flag2)
					target=(String)vector.get(++counter);
			}  

		return target;
	}

	public void saveAll()
	{
		try{
			 file = new File("TelephoneDirectory.txt");
			 RandomAccessFile raf=new RandomAccessFile(file,"rw");
			 raf.seek(raf.length());
			 for(int iterator=0;iterator<vector.size();iterator++)
			   raf.writeUTF((String) vector.get(iterator));
	  }
	  catch(IOException ee)
	  {
		  System.out.println("There is A problem with this File "+file);
	  }

	}

}

أرجو أن تكون المتابعة سهلة،،

بالتوفيق،، ونتطلع إلى مشاركات جميلة مثل هذه!

#3

حياك الله ابو مازن

الله يجزاك خير والله اني فرحت جداً لملاحظاتك وتعديلاتك خاصة مسألة Listeners

:blink: يبيلي يومين أتفحص الكود عشان أتعلم مثل هذه الأمور

هذي فايدة وجود الخبراء امثالك :)

استخدمت Vector لأني ناوي أطور الPattern ليحتوي أكثر من معلومتين

ابو مازن ودي استغل فرصة وجودك و أسألك

أنا طالب عندي مشروع تخرج ، هل عندك أي فكرة مشروع تخرج ، يعني مابي فيها ذكاء اصطناعي أو شي معقد مره

خلفيتي في الجافا DataStructurs & Gui component والتعامل مع قاعدة البيانات اوراكل

ولابد اطرح فكرتي على الدكتور يوم الاثنين ،

والPattern ابي أفصله وارجع في أي اشكاليه توقف أمامي :huh:

تم تعديل هذه المشاركة بواسطة {عيسى} في 8 أكتوبر 2006 في 00:16

#4

بالنسبة لبياناتك فاجعلها في PersonInfo Class

وبعدها ضعها في Map

بالتوفيق في مشروعك!

هذا الموضوع مغلق.

مواضيع مشابهة