Design idea - Part I - fledgling

Posted by xoligy on Sat, 23 Oct 2021 13:25:46 +0200

MoCha design idea - Part I

The content of this article is the content recorded when I first learned Java. Now it's very interesting to look back.

1) The design idea limits the parameter range of interface call

  If we want to limit the parameter entry range of a method
  You can set the parameter type of the method to be smaller, and then call a method with similar functions inside the method
  The parameter entry range of this function similar method is larger than the method parameter range we set

Extended thinking:
  You can set the method we set to public
  Set the internally called method to private
  In this way, the external class can only assign values to parameters by calling the methods we set
  A wider range of methods are inaccessible to others

2) The design idea is to use the Properties class to read the configuration file

 * Use the Properties property collection and IO stream (InputStream and Reader can be used)
 * When the execution of a module reaches a certain scale, it is designed to turn to another operation
Properties prop = new Properties();
Reader reader = new FileReader("Count.txt");

prop.load(reader); // You can receive either a reader or an InputStream

String value = prop.getProperty("count");
int number = Integer.parseInt(value);

if(number > 5){
	// Output prompt
} else{
	// Otherwise, execute the module statement

3) Thread safety in multithreading

Set and get the resources of the thread should be the same resource (design idea)

So the problem is, how to achieve it?
	Implementation scheme:
		Create this resource in the outside world and pass it to other classes through the parameters of the construction method
		This resource is then used as a lock (usually passed to other thread objects as construction parameters)

4) Producers and consumers of design ideas

After the lock object waits,"Release the lock immediately" . When you wake up, wake up from this place

The wake-up of the lock object does not mean that it can be executed immediately, but must be robbed CPU Time slice
boolean flag; // The default value is false

/** producer */
public synchronized void set(String name, int age){
	// If there is data, wait
		try {
		} catch (InterruptedException e) {
	// production data = name;
	this.age = age;
	this.flag = true; // After production, there will be data, so it is true
	this.notify(); // Awaken consumers

/** consumer */
public synchronized void get(){
		try {
		} catch (InterruptedException e) {
	/*-- This is consumer behavior-*/
	System.out.println( + " --- " + this.age);
	this.flag = false; // After consumption, there is no data, so it is false

5) On the problem of file copy and deletion

Copying and deleting files
	enhance for Circulation File[] fileArray = file.listFiles();
Use together

6) The design idea is in GUI. How to make good use of API? (find methods or classes we don't know)

for example:
(1)get colors , Can find Color General class -> Color.BLACK

(2)Want to use in the program dos command , Can find Runtime General class 
	--> Runtime rt = Runtime.getRuntime()
				rt.exec(String command)	
(3)Want to get the toolkit , Can find Toolkit
	Toolkit tk = Toolkit.getDefaultToolkit(); // Get the default Toolkit, and the return value is the Toolkit type
	// This method returns a Dimension object that encapsulates the width and height of a single component		
	Dimension d = tk.getScreenSize(); // Gets the size of the screen
   * Get the picture object according to the path. The return value type of this method is Image
   * be careful!!! The path of the picture is the full path
	Image i = tk.getImage("src\\source\\Leisure desktop.jpg");

7) How to center the coordinate position of JFrame form?

 * Center the coordinate position of the JFrame form
 * How to center the coordinate position of JFrame form?
 * Idea:
 * 1: Gets the width and height of the JFrame form
 * 2: Gets the width and height of the screen
 * 3: Set (width of screen - width of JFrame form) / 2
 * 	  (Height of screen - height of JFrame form) / 2
 * 	 As the new coordinates of the JFrame form
 * @param jf	JFrame Form Object 
public static void setLocation(JFrame jf){
	// To get the width and height of the screen, you have to use the Toolkit
	Toolkit tk = Toolkit.getDefaultToolkit();
	// Get the width and height of the screen. This method returns a Dimension object that encapsulates the width and height of a single component
	Dimension d = tk.getScreenSize();
	double screenWidth = d.getWidth();//The method returns double
	double screenHeight = d.getHeight();
	/** Gets the width and height of the JFrame form */
	int jfWidth = jf.getWidth();
	int jfHeight = jf.getHeight();
	/** JFrame New coordinates of the form */
	int x = (int)(screenWidth - jfWidth)/2;
	int y = (int)(screenHeight - jfHeight)/2;
	jf.setLocation(x, y);

8) User login and registration of IO version of design idea

The key is how to set rules to store information in the user table and how to read information from the user table

* Register users
* We need to define a rule
* User information consists of the following formats:
* userName=passWord
* @param user
public static void register(User user){
	BufferedWriter bw = null;
	// Pay attention to appending information to the user table
	try {
		bw = new BufferedWriter(new FileWriter(file , true));
		bw.write(user.getUserName() + "=" +user.getPassWord());
	} catch (IOException e) {
	}finally {
			try {
			} catch (IOException e) {

* User login function
* @param name		user name
* @param passWord	User password
public static boolean login(String name , String passWord){
	boolean flag = false;
	BufferedReader br = null;
	try {
		br = new BufferedReader(new FileReader(file));
		String line = null;
		while((line = br.readLine())!= null){
			String[] messageS = line.split("=");
			if(messageS[0].equals(name) && messageS[1].equals(passWord)){
				flag = true;
		// Match the user information and log in
	} catch (IOException e) {
	} finally {
			try {
			} catch (IOException e) {
	return flag; // Information mismatch, login failed

9) User login and registration of collective version of design idea

The key is to statically load ArrayList < user > from the beginning and traverse ArrayList

/** In order to unify the objects of the collection during registration and login, we define the collection as a member variable */
/** In order not to be seen by outsiders, we set the collection storing user information to private */
/** In order to enable objects to share stored user information, we set the collection to static */
private static ArrayList<User> list = new ArrayList<User>();

// Judge whether the user's information matches when logging in. If not, return false
public boolean login(String name, String passWord) {
	for (User user : list) {
		if (user.getUserName().equals(name) 
				&& user.getPassWord().equals(passWord)) {
			return true;
	return false;

// Store the registered user information in the collection
public void register(User user) {

10) Design ideas about GUI design

  Register control 
  Set mouse style usage code: 
  lblRegister.setCursor(new Cursor(Cursor.HAND_CURSOR)); // You can turn the mouse into a grip

(2)"<html><u>Register</u><html>"You can underline label text

(3)How to close a subform? - Subform to be on the desktop panel, Added to the menu bar is MenuItem , no Menu
	MDIChild .setClosable();

(4)How to make a subform have only one?(The following code is in the main interface)
	private JInternalFrame inFrame = null;
	(In the listening event of the subform)
	if(inFrame!=null){	//This indicates that there is a subform
	JInternalOper f1 = new JInternalOper();
	inFrame = f1;

11) Design idea: if a class has no construction method

If a class has no constructor, Then there are the following situations:
	(1)Members are static, as(Math ,Arrays ,Collections)
	(2)Singleton design pattern, as(Runtime)
	(3)Class has static methods that return objects of this class(InetAddress)
      class Demo{
        private Demo(){}
        public static Demo getXxx(){
          return new Demo();

12) How does the design idea reverse the text in the IO stream?

(1)Create input / output stream
(2)Create collection object
(3)Store the read data into the collection
(4)Traversing the set upside down
(5)Closed flow

13) . design idea: add data of other data types in ArrayList < integer >

If you want to add data of other data types in ArrayList < integer >, can you do this? How?
	Realized by reflection principle
* Using the reflection principle
* (1)Get the Class object of ArrayList - the object has been provided here, so you can call getClass() directly through the object
* (2)Get the add method through the Class object and use
* Analyze why elements can be added across generics through the reflection principle
* Because: the role of generics is mainly reflected during compilation, which can effectively avoid the addition of wrong data types
* In fact, the parameters of the add (E) method of the collection are of type E, that is, during code execution
* Method parameter types have no effect. You can put other types of data, strings, or even objects of a class
* What reflection does is start with the Class object of the ArrayList collection object
* Get the add (E) method of the collection to use directly
* The effect is equivalent to removing generics
Code example:
	ArrayList<Integer> list = new ArrayList<Integer>();
	Class c = list.getClass();
	Method m = c.getDeclaredMethod("add", Object.class);
	m.invoke(list , "hello");

	Student stu = new Student();	
	m.invoke(list , stu);

// Output results:
	[hello, Student [name = null, age = 0, id = null]]

14) The design idea uses the reflection principle to set values for any field of any object

 * Implement setting values for any field of any object
 * @param obj	The object that contains the field
 * @param name	Field name to assign
 * @param value	The value to assign to the field
 * @throws Exception 
public static void setProperties(Object obj, String name , Object value) throws Exception{
	// Get Class object
	Class c = obj.getClass();
	// Obtain the specified field through the Class object. Because the obtained field may have access restrictions, violent access must be taken
	Field f = c.getDeclaredField(name);
	f.set(obj, value);

15) How to read the configuration file gracefully?

// How do I read a configuration file?
		InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("properties.txt");
		Properties prop = new Properties();
		String driverClass = prop.getProperty("driverClass");
		String url = prop.getProperty("url");
		String user = prop.getProperty("user");
		String password = prop.getProperty("password");	
// Application of profile in reflection:
* Run profile content using reflection
* 1: Create Properties property set
* 2: Load the configuration file into the property set through the load() method
* 3: Get data from property set
Properties prop = new Properties();
FileReader fr = new FileReader("class.txt");

// Get the corresponding value from the key value of the property set
String className = prop.getProperty("className");
String MethodName = prop.getProperty("MethodName");

// Pay attention to the class name and path in the configuration file
Class c = Class.forName(className);
Constructor con = c.getDeclaredConstructor();
Object obj = con.newInstance();

Method m = c.getDeclaredMethod(MethodName);

16) The design idea is how to send the information from one client to other clients

// In order to send the information sent by the client to other clients, we first store each client in the collection
ArrayList<Client> clients = new ArrayList<Client>();

s = ss.accept();
Client client = new Client(s);
clients.add(client); // Add client to collection
new Thread(client).start();

Define an internal class implementation Runnable Interface
private class Client implements Runnable{...}

17) How to copy files faster?

(1)Copy file:
Code example:(Just one statement)
  Files.copy(Paths.get("a.txt"), new FileOutputStream("g.txt"));
(2)Write set data to file
 Code example:
  ArrayList<String> list = new ArrayList<String>();
  list.add("Ze Feng Yang");

  Files.write(Paths.get("g.txt"), list, Charset.forName("GBK"));

18) Compilation Rules of tools for design ideas

(1) If there are static methods in the tool class, the constructor is used private Or use abstract To decorate
	Force the caller to call the tool method directly using the class name(Arrays,Collections)
(2) If there are no static methods in the tool class, the tool class is designed as a singleton pattern

19) Judge whether a document conforms to a certain type of regulations

Upload type constraint:{
// =====Mode 1:=====

private static final String ALLOWED_IMAGE_TYPE = "jpg;png;gif";

//Before formally processing the upload control, first judge whether the file meets the type we want
String[] types = ALLOWED_IMAGE_TYPE.split(";");  // Because an array cannot directly determine whether an element is included in it
boolean isType = Arrays.asList(types).contains(FilenameUtils.getExtension(FilenameUtils.getName(item.getName())));
// We first convert the array into a List set, and then judge it through the contains() method in the set

	req.setAttribute("errorMes", "Coder,You haven't selected the file correctly");
	req.getRequestDispatcher("upload.jsp").forward(req, resp);

// =====Mode 2:======
 *	Put a file name (including extension) into getMimeType(), and the corresponding MIME type will be returned
 *	It can be used to judge whether it conforms to a certain type
 *	We just need to determine whether to prefix this type
String type = super.getServletContext().getMimeType(FilenameUtils.getName(item.getName()));
boolean isType = type.startsWith("image/");	

20) Custom exception class of design idea

 * Logical exception class
 * @author MoCha
public class LogicException extends RuntimeException {
	private static final long serialVersionUID = 1L;
	 * @param message	Abnormal information
	public LogicException(String message) {
	 * @param message	Abnormal information
	 * @param cause		Root cause of abnormality
	public LogicException(String message, Throwable cause) {
		super(message, cause);

21) data structure in web based on design idea

stay WEB The most used structure in the application is Map,key=value This form

22) reflection of design ideas is used in combination with configuration files

Reflection works in conjunction with configuration files

Topics: Java Back-end