Design Principles--Encapsulation Change Principles

Package change points . The advantage of isolating change points is that it isolates the frequently changing parts of the system from the stable parts, which helps to increase reusability and reduce system coupling. The intent of many design patterns is to clearly point out their solution to a problem, and the point of learning a design pattern is to discover the point of change encapsulated in its solution.

abstract class Person{
 //Simply given two properties, name and gender
 protected String name="";
 protected String sex = "";
 
 public Person(String name,String sex){
  this.name = name;
  this.sex = sex;
 }
 
 /*
  * Both men and women have the behavior of walking
  * */
 public void run(){
  System.out.println(this.name+"走路");
 }
 
 public void eat(){
  System.out.println(this.name+"吃饭");
 }
 
 public abstract void method();
}
class Man extends Person{

 public Man(String name, String sex) {
  super(name, sex);
  System.out.println("Initialize male siblings");
 }
 
 /**
  * This is a male-specific behavior, fighting (of course women can also fight, we only assume that men will fight)
  */
 public  void method(){
  System.out.println(this.name+"Join the battle");
 }
}




class Women extends Person{

 public Women(String name, String sex) {
  super(name, sex);
  System.out.println("Initialize female siblings");
 }

 /**
  * Female fertile behavior
  */
 public  void method(){
  System.out.println(this.name+"children");
 }
}

  

public class Hello{
 public static void main(String[] args) {
  Person man = new Man("zhangsan", "male");
  man.eat();
  man.run();
  man.method();
  
  Person women = new Women("zhangsan", "male");
  women.eat();
  women.run();
  women.method();
 }
}

 

Since person is mutable, we abstractly encapsulate it, and man and women inherit it respectively.
So how do we make it mutable? Deriving different subclasses is a kind of mutable, or more strictly an extension.

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326453994&siteId=291194637