day23 Java design pattern network programming

Posted by djnrempel on Wed, 27 Oct 2021 03:06:48 +0200

I know, i know
You accompany me on the other side of the earth




1, Design pattern

1. Simple factory mode (static factory method mode)

/*
Simple factory mode (static factory method mode)

    advantage
        The client does not need to be responsible for the creation of objects, so as to clarify the responsibilities of each class
    shortcoming
        This static factory class is responsible for creating all objects. If new objects are added,
        Or if some objects are created in different ways, you need to constantly modify the factory class, which is not conducive to later maintenance
 */
public class AnimalDemo {
    public static void main(String[] args) {
        //Improved version
        Animal dog = AnimalFactory.createAnimal("Dog");
        dog.eat();
        Animal cat = AnimalFactory.createAnimal("Cat");
        cat.eat();

        Animal pig = AnimalFactory.createAnimal("Pig");
        if(pig!=null){
            pig.eat();
        }else {
            System.out.println("The factory does not yet provide the function of manufacturing this object!");
        }
    }
}

Total abstract class Animal

public abstract class Animal {
    //eat
    public abstract void eat();
}

Implementation class Cat

public class Cat extends Animal {
    @Override
    public void eat() {
        System.out.println("Cats eat fish");
    }
}

Implementation class Dog

public class Dog extends Animal {
    @Override
    public void eat() {
        System.out.println("Dogs eat meat");
    }
}

Static factory method class

public class AnimalFactory {
    //The privatization of constructor makes it impossible for external to create this kind of object
    private AnimalFactory(){
    }
    public static Animal createAnimal(String type){
        if("Cat".equals(type)){
            return new Cat();
        }else if("Dog".equals(type)){
            return new Dog();
        }else {
            return null;
        }
    }
}

2. Simple factory mode (static factory method mode)

/*
Factory method model

    advantage
        The client does not need to be responsible for the creation of objects, so as to clarify the responsibilities of each class,
        If a new object is added, you only need to add a specific class and a specific factory class,
        It does not affect the existing code, easy to maintain in the later stage, and enhances the scalability of the system
    shortcoming
        Additional coding is required, which increases the workload
 */
public class AnimalDemo {
    public static void main(String[] args) {
        //I want a dog
        DogFactory dogFactory = new DogFactory();
        Animal animal = dogFactory.creatCreateAnimal();
        animal.eat();

        //I want a cat
        CatFactory catFactory = new CatFactory();
        Animal animal1 = catFactory.creatCreateAnimal();
        animal1.eat();
    }
}

Total abstract class Animal

public abstract class Animal {
    public abstract void eat();
}

Implementation class Cat

public class Cat extends Animal {
    @Override
    public void eat() {
        System.out.println("Cats eat fish");
    }
}

Implementation class Dog

public class Dog extends Animal {
    @Override
    public void eat() {
        System.out.println("Dogs eat meat");
    }
}

Cat factory

public class CatFactory implements Factory{
    @Override
    public Animal creatCreateAnimal() {
        return new Cat();
    }
}

Dog factory

public class DogFactory implements Factory {
    @Override
    public Animal creatCreateAnimal() {
        return new Dog();
    }
}

3. Singleton mode (hungry and lazy)

Hungry Han style

/*
        Singleton mode: ensure that there is only one object in the class

        How to ensure that a class has only one object in memory?
            1,Construction method private
            2,Create an object at the location of the member variable of the class
            3,Provide a public method to get the object to the outside world

        Through observation, we found that as soon as the class is loaded, the object is created
        Such a method is the hungry Chinese style in the singleton mode.
 */
public class StudentDemo {
    public static void main(String[] args) {
        Student s1 = Student.getStudent();
        Student s2 = Student.getStudent();

        System.out.println(s1==s2);
        System.out.println(s1);
        System.out.println(s2);
    }
}
public class Student {
    private static Student s = new Student();
    
    private Student(){
    }
    public static Student getStudent(){
        return s;
    }
}

Lazy style

/*
        How to ensure that a class has only one object in memory?
            1,Construction method private
            2,Create an object at the location of the member variable of the class
            3,Provide a public method to get the object to the outside world

        Hungry Chinese style: create an object as soon as the class is loaded
        Lazy: create objects when you use them.
            1,Lazy loading (delayed loading)
            2,Prone to thread safety problems
                1)Is there a multithreaded environment
                2)Is there a shared variable
                3)Are there multiple statements that operate on shared variables
 */
public class TeacherDemo {
    public static void main(String[] args) {
        Teacher t1 = Teacher.getTeacher();
        Teacher t2 = Teacher.getTeacher();

        System.out.println(t1==t2);
        System.out.println(t1);
        System.out.println(t2);
    }
}
public class Teacher {
    private Teacher(){
    }

    private static Teacher t = null;
    
    //Static synchronization method
    public synchronized static Teacher getTeacher(){
            //t1,t2,t3
            if(t == null){
                t = new Teacher();
            }
            return t;
        }
}

2, Network programming

It is used to realize the data exchange between programs running on different computers

Three elements of network communication

IP address
InetAddress, the identification of the device in the network, which is not easy to remember, and the available host name
Port number
It is used to identify the logical address of the process and the identification of different processes
transport protocol
Communication rules, common protocols: TCP, UDP


3, Protocol UDP & TCP

1,UDP

Encapsulate the data source and destination into data packets without establishing a connection;
The size of each datagram packet is limited to 64k; Because there is no connection, it is an unreliable protocol;
No need to establish a connection, fast

Data received by UDP protocol receiver:

        1,Create the of the receiving end Socket object
        2,Create a receive packet (receive data container)
        3,call Socket Receiving method for receiving data  receive()
        4,Analyze the data package, obtain the data and display it on the console
        5,Free resources, close Socket
public class Receive1 {

    public static void main(String[] args) throws Exception {
        //Create the Socket object of the receiving end
        //DatagramSocket(int port)
        //Construct a datagram socket and bind it to the specified port on the local host
        DatagramSocket ds = new DatagramSocket(2222);

        //Specifies the size of the byte array that can be received
        byte[] bytes = new byte[1024];
        int length = bytes.length;

        //DatagramPacket(byte[] buf, int length)
        //Construct a datagram packet to receive the packet length of the length
        DatagramPacket dp = new DatagramPacket(bytes, length);

        //public void receive(DatagramPacket p)
        //Call the Socket receiving method to receive data
        //The method blocks until a packet is received
        ds.receive(dp);

        //public InetAddress getAddress()
        // Returns the IP address of the computer that sent or received the datagram.
        InetAddress address = dp.getAddress();

        //Parse the data packet and obtain the data
        //public byte[] getData() returns the data buffer
        byte[] data = dp.getData();

        //public int getLength()
        // Returns the length of data to be sent or received
        int length1 = dp.getLength();

        String s = new String(data, 0, length1);
        System.out.println(address+":"+s);

        //Release resources and close the Socket
        ds.close();
    }
}

UDP protocol sender sends data

   		1,Establish the sender's Socket object
    	2,Create and package data
    	3,By calling Socket The sending method sends the data packet
    	4,Free resources, close Socket
public class Send1 {

    public static void main(String[] args) throws Exception{
        //Create the Socket object DatagramSocket of UDP sender
        //DatagramSocket()
        //Construct a datagram socket and bind it to any available port on the local host
        DatagramSocket ds = new DatagramSocket();

        byte[] bytes = "Leek box ".getBytes();
        int length = bytes.length;

        //Specify the IP address of the sender / 192.168.2.151
        InetAddress address = InetAddress.getByName("192.168.2.151");

        //Port number
        //Valid ports: 0 ~ 65535, of which 0 ~ 1024 are used or reserved by the system
        int port = 2222;

        //Create data
        //DatagramPacket(byte[] buf, int length, 
        //							InetAddress address, int port)
        //Constructs a datagram for sending packets of length. Packet length specifies the port number on the specified host.
        DatagramPacket dp = new DatagramPacket(bytes,length,address,port);

        //void send(DatagramPacket p)
        //Send datagram from this socket
        ds.send(dp);

        //Release resources and close the Socket
        ds.close();


    }
}

2,TCP

Establish a connection to form a data transmission channel; Large amount of data transmission in connection;
The connection is completed through three handshakes, which is a reliable protocol;
The connection must be established, and the efficiency will be slightly lower

TCP protocol receiving data server

    	1,Create server-side Socket object ServerSocket
    	2,Listen to the client connection and return a corresponding client connection Socket object
   		3,Get the input stream object, read the data and display it on the console
    	4,Release resources
    	
    	        An error is reported when the client is started before the server is started:
        	java.net.ConnectException: Connection refused: connect
        		connection not permitted

    		TCP The protocol must start the server first
public class Server1 {

    public static void main(String[] args) throws Exception{

        //Create a server-side Socket object ServerSocket
        //ServerSocket(int port)
        //Creates a server socket bound to the specified port
        ServerSocket ss = new ServerSocket(5555);

        //Listen to the client connection and return a Socket object of the corresponding client
        //public Socket accept()
        // Listen for the socket you want to connect to and accept it
        //This method blocks until a connection is established
        Socket accept = ss.accept();

        //Get the input stream object, read the data and display it on the console
        //public InputStream getInputStream()
        //Returns the input stream for this socket
        InputStream is = accept.getInputStream();
        byte[] bytes = new byte[1024];
        int length = is.read(bytes);

        String s = new String(bytes, 0, length);

        //Get who sent the information, IP
        //public InetAddress getInetAddress() returns the address to which the socket is connected.
        //Returns the address of the client
        InetAddress ia = accept.getInetAddress();

        System.out.println(ia+": "+s);

        //Release resources
        accept.close();
    }
}

TCP protocol transmission sending data terminal

    	1,Create client's Socket object
        	Specifies the name of the server IP And ports, internal automatic connection
        	Once the connection is established successfully, explain the connection with the service IO Channel formation
    	2,Get the output stream to IO Channel write data
    	3,Release resources
public class Client1 {

    public static void main(String[] args) throws Exception{

        Socket s = new Socket("192.168.2.151",5555);

        //Get output stream
        //public OutputStream getOutputStream()
        //Returns the output stream of this socket
        OutputStream os = s.getOutputStream();
        os.write("Leek box".getBytes());

        //Release resources
        s.close();
    }
}

summary

UDP: no connection required

Server side
1,new DatagramSocket (int port)
Specify the interface and establish the connection

2,new DatagramPacket (byte[] buf, int length)
Create a package to receive data

3,receive(DatagramPacket p)
receive data

4,getData ()
get data

5,close ()
Release resources

Sender
1,new DatagramSocket ()
Establish connection

2,new DatagramPacket(byte[] buf, int length, InetAddress address, int port)
Create package

3,send(DatagramPacket p)
Send packet

4,close ()
Release resources

TCP: establish connection, three handshakes
Note: the server side needs to be established first to determine the interface number

Server side
1,new ServerSocket (int port)
Specify a port number to create a server connection

2,accept ()
Listen to the client connection and know that it is blocked before obtaining the sender data

3,getInputStream () getInetAddress()
Get the input stream and read the data / ip address of the sender

4,close ()
Release resources

Sender
1,Socket (String host, int port)
Create a client interface and specify the ip and port number of the receiving end

2,getOutputStream()
Get the output stream and write the issued information

3,close ()
Release resources

Topics: Java