zoukankan      html  css  js  c++  java
  • java程序设计单一原则

    在我的程序设计中一般一个类就负责一个职责

    ex:

      class Animal{

        public void brether(String animal){

          System.out.println(animal+"呼吸空气");

        }

      }

      

      class Test{

        public static void main(String []args){

          Animal animal=new Animal();

           animal.brether("狗");

        }

      }

    package com.huawei.entity;
    
    public class Animal {
    
        //单一功能的类
        public void breathe(String animal){
            System.out.println(animal+"呼吸空气");
        }
        
        public static void main(String[] args) {
            //当以方式
    //        Animal animal=new Animal();
    //        animal.breathe("猪");
    //        animal.breathe("狗");
    //        animal.breathe("牛");
            //修改类
    //        Terrestrial terrestrial=new Terrestrial();
    //        terrestrial.breath("狗");
    //        terrestrial.breath("猪");
    //        terrestrial.breath("牛");
    //        Aquatic aquatic=new Aquatic();
    //        aquatic.breath("鱼");
            //修改方法
            Animal2 animal2=new Animal2();
            animal2.breadthe("鱼");
            animal2.breadthe("猪");
            animal2.breadthe("狗");
            animal2.breadthe("牛");
            animal2.breadthe("羊");
            
        }
        /**
         * 程序出现问题,如果是鱼,就违背原则了
         */
        
        //将动物分成水陆两类
        
    }
    //陆生动物
    class Terrestrial{
        public void breath(String animal){
            System.out.println(animal+"用空气呼吸");
        }
    }
    
    //水生动物
    class Aquatic{
        public void breath(String animal){
            System.out.println(animal+"用水呼吸");
        }
    }
    
    //修改方法
    class Animal2{
        public void breadthe(String animal){
            if(animal.equals("鱼")){
                System.out.println(animal+"用水呼吸");
            }else{
                System.out.println(animal+"用空气呼吸");
            }
        }
    }

    当我们的类需要修改的时候可以根据以上具体情况进行修改

    建议还是修改类,将类拆分,这样满足单一职责原则

    ,如果类比较简单,建议在方法上改,该类本身,这样比较简单

    开销少

    拆分类开销大,具体问题具体分析

  • 相关阅读:
    [JSOI2007][BZOJ1031] 字符加密Cipher|后缀数组
    leetcode Flatten Binary Tree to Linked List
    leetcode Pascal's Triangle
    leetcode Triangle
    leetcode Valid Palindrome
    leetcode Word Ladder
    leetcode Longest Consecutive Sequence
    leetcode Sum Root to Leaf Numbers
    leetcode Clone Graph
    leetcode Evaluate Reverse Polish Notation
  • 原文地址:https://www.cnblogs.com/javaweb2/p/6243738.html
Copyright © 2011-2022 走看看