Web學(xué)習(xí)筆記 - 第009天

創(chuàng)建對象

1. 構(gòu)造器創(chuàng)建對象

        Student stu1 = new Student("kygo", 100);
        System.out.println(stu1);

2. 通過克隆創(chuàng)建對象(內(nèi)存復(fù)制)
實(shí)現(xiàn)Cloneable接口满败,重寫clone()方法

    @Override
    public Object clone() {
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            throw new RuntimeException();
        }
    }

測試

        Student stu2 = (Student) stu1.clone();
        System.out.println(stu2);

3. 通過反序列化創(chuàng)建對象(從流中讀取對象)
實(shí)現(xiàn)序列化接口Serializable

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(out);
        oos.writeObject(stu2);
        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(in);
        Student stu3 = (Student) ois.readObject();
        System.out.println(stu3);

4. 通過反射(reflection)創(chuàng)建對象
拿到一個類的原始數(shù)據(jù)類對象
1.根據(jù)路徑

        Class<?> clazz1 = Class.forName("com.kygo.Student");

2.用類.class

        Class<?> clazz2 = Student.class;

3.用類對象實(shí)例的getClass()方法

        Class<?> clazz3 = stu3.getClass();

根據(jù)類的類對象可以創(chuàng)建這個類的對象實(shí)例

        Student stu4 = (Student) clazz1.newInstance();

根據(jù)類的類對象使用getConstructor()方法的到這個類的構(gòu)造器赏陵,使用構(gòu)造器可以創(chuàng)建對象

        Constructor<?> constructor = clazz2.getConstructor(String.class, int.class);
        Student stu5 = (Student) constructor.newInstance("wang Dachui", 18);

測試:

        Class<?> clazz1 = Class.forName("com.kygo.Student");
        Class<?> clazz2 = Student.class;
        Class<?> clazz3 = stu3.getClass();
        // System.out.println(clazz1 == clazz2);   // true
        // System.out.println(clazz2 == clazz3);   // true
        Student stu4 = (Student) clazz1.newInstance();
        System.out.println(stu4);
        // System.out.println(stu4.getName());
        Constructor<?> constructor = clazz2.getConstructor(String.class, int.class);
        Student stu5 = (Student) constructor.newInstance("wang Dachui", 18);
        System.out.println(stu5);
        // System.out.println(stu5.getName());
        // System.out.println(stu5.getAge());
        Constructor<?>[] constructors = clazz3.getConstructors();
        for (Constructor<?> temp : constructors) {
            Student stu6 = (Student) temp.newInstance();
            System.out.println(stu6);
        }

設(shè)計(jì)模式

單例

單例 - 讓一個類只能創(chuàng)建出一個對象(服務(wù)器上常用)

  1. 將構(gòu)造器私有(不允許直接使用構(gòu)造器創(chuàng)建對象)
  2. 通過公開的靜態(tài)的方法向外界返回該類的唯一實(shí)例
餓漢式單例
public class StudentManager {
    private static StudentManager instance = new StudentManager();
    
    // ...
    
    private StudentManager() {
    }
    
    public static StudentManager getInstance() {
        return instance;
    }
    
    // ...
}
懶漢式單例(懶加載單例)
public class StudentManager {
    private static StudentManager instance = null;
    
    // ...
    
    private StudentManager() {
    }
    
    public static synchronized StudentManager getInstance() {
        if (instance == null) {
            instance = new StudentManager();
        }
        return instance;
    }
    
    // ...
}
登記式單例
public class ServiceFactory {
    private static Map<Class<?>, Object> map = new HashMap<>();
    // 登記式單例
    static {
        map.put(DeptService.class, 
                ServiceProxy.getProxyInstance(new DeptServiceImpl()));
        map.put(EmpService.class, 
                ServiceProxy.getProxyInstance(new EmpServiceImpl()));
    }
    
    private ServiceFactory() {
        throw new AssertionError();
    }
    
    public static Object factory(Class<?> serviceType) {
        return map.get(serviceType);
    }
}

一般類里面沒有狀態(tài)屬性都可以改造成單例模式類

簡單工廠模式

簡單工廠模式(靜態(tài)工廠模式)
將對象的實(shí)例化過通過工廠方法隱藏起來
使得對象的使用者可以和具體的對象以及創(chuàng)建對象的過程解耦合

例子1:在工廠用構(gòu)造器創(chuàng)建對象

工廠類:

public class FruitFactory {
    
    public static Fruit factory(String type) {
        Fruit fruit = null;
        switch (type.toLowerCase()) {
        case "apple":
            fruit = new Apple();
            break;
        case "banana":
            fruit = new Banana();
            break;
        case "durian":
            fruit = new Durian();
            break;
        }
        return fruit;
    }
}

測試:

        Fruit apple = FruitFactory.factory("apple");
        Fruit durian = FruitFactory.factory("durian");
        Fruit grape = FruitFactory.factory("grape");
        System.out.println(apple);
        System.out.println(durian);
        System.out.println(grape);

例子2:使用反射

工廠類:

public class FruitFactory {
    
    public static Fruit factory(String className) {
        try {
            Class<?> clazz = Class.forName(className);
            return (Fruit) clazz.newInstance();
        } catch (Exception e) {
            // throw new RuntimeException();
            return null;
        }
    }
    
    public static Fruit factory(Class<?> fruitType) {
        try {
            return (Fruit) fruitType.newInstance();
        } catch (Exception e) {
            throw new RuntimeException();
        }
    }
}

測試:

        Fruit apple = FruitFactory.factory(Apple.class);
        Fruit durian = FruitFactory.factory(Durian.class);
        Fruit grape = FruitFactory.factory("com.kygo.Grape");
        System.out.println(apple);
        System.out.println(durian);
        System.out.println(grape);

動態(tài)代理

JDK 1.3引入了動態(tài)代理機(jī)制 - 可以通過反射的方式動態(tài)生成代理對象
InvocationHandler - invoke(Object, Method, Object[])
Proxy類 - newProxyInstance(ClassLoader, Class<?>[], InvocationHandler)

舊做法:創(chuàng)建代理類并實(shí)現(xiàn)要代理的類相同的接口喷舀,重寫接口方法艺演,在要代理的方法亲澡,添加自己的東西(日志等)
例子1:考生找槍手代考
考生接口:

public interface Candidate {

    public void joinExam();
}

人類:

public class Person {
    protected String name;
    
    public Person(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
}

懶學(xué)生:

public class LazyStudent extends Person implements Candidate {
    
    public LazyStudent(String name) {
        super(name);
    }

    @Override
    public void joinExam() {
        System.out.println("姓名: " + name);
    }
}

槍手:

public class ExamAgent extends Person implements Candidate {
    private Candidate target;
    
    public ExamAgent(String name) {
        super(name);
    }
    
    public void setTarget(Candidate target) {
        this.target = target;
    }
    
    @Override
    public void joinExam() {
        target.joinExam();
        System.out.println(name + "奮筆疾書答案.");
        System.out.println(name + "答題完畢交卷.");
    }
}

測試:

        LazyStudent student = new LazyStudent("王大錘");
        ExamAgent agent = new ExamAgent("駱昊");
        agent.setTarget(student);
        agent.joinExam();

現(xiàn)在:

  • 第一步 創(chuàng)建代理類并實(shí)現(xiàn)InvocationHandler的接口
class ListProxy<E> implements InvocationHandler
  • 第二步 添加被代理對象的屬性姥芥,和代理對象的構(gòu)造器 - 單例
        private Object target; // 被代理的對象(目標(biāo)對象)
        
        private ListProxy(Object target) {
            this.target = target;
        }
  • 第二步 實(shí)現(xiàn)靜態(tài)方法getProxyInstance()拿到代理類對象
    通過Proxy工具類的newProxyInstance方法生成動態(tài)代理
        public static <E> Object getProxyInstance(Object target) {
            Class<?> clazz = target.getClass();
            // 通過Proxy工具類的newProxyInstance方法生成動態(tài)代理
            // 第一個參數(shù)是被代理對象的類加載器
            // 第二個參數(shù)是被代理對象實(shí)現(xiàn)的接口(被代理對象和代理對象要實(shí)現(xiàn)相同的接口)
            // 第三個參數(shù)是實(shí)現(xiàn)了InvocationHandler接口的對象
            return Proxy.newProxyInstance(clazz.getClassLoader(), 
                    clazz.getInterfaces(), new ListProxy<E>(target));
        }
  • 第三步 重寫回調(diào)方法invoke()
    InvocationHandler接口(單方法接口/函數(shù)式接口)中的invoke方法是一個回調(diào)方法
    當(dāng)執(zhí)行被代理對象target的任何一個方法時不是直接執(zhí)行而是回調(diào)代理對象的invoke方法
    該方法的第二個參數(shù)代表了需要執(zhí)行的方法 第三個參數(shù)是執(zhí)行方法時傳入的參數(shù)
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
        // InvocationHandler接口(單方法接口/函數(shù)式接口)中的invoke方法是一個回調(diào)方法
        // 當(dāng)執(zhí)行被代理對象target的任何一個方法時不是直接執(zhí)行而是回調(diào)代理對象的invoke方法
        // 該方法的第二個參數(shù)代表了需要執(zhí)行的方法 第三個參數(shù)是執(zhí)行方法時傳入的參數(shù)
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            // 被代理對象的所有方法都要通過代理對象來幫它調(diào)用執(zhí)行
            // 調(diào)用被代理對象的方法 第一個參數(shù)是被代理的對象 第二個參數(shù)是方法參數(shù)
            // 如果被代理對象當(dāng)前要執(zhí)行的方法沒有參數(shù)那么args的值就是null
            // 如果被代理對象的方法有返回值那么retValue就保存該返回值
            // 如果被代理對象的方法沒有返回值那么retValue的值就是null
            Object retValue = method.invoke(target, args);
            // 如果執(zhí)行的方法名以add据悔、remove幼驶、clear艾杏、retain打頭
            // 那么通過下面代碼給這些方法增加在控制臺打印日志的功能
            String methodName = method.getName();
            // System.out.println("正在執(zhí)行" + methodName + "方法");
            if (methodName.startsWith("add") || methodName.startsWith("remove")
                    || methodName.startsWith("clear") || methodName.startsWith("retain")) {
                if (target instanceof List) {
                    List<E> list = (List<E>) target;
                    // 以下代碼就是代理對象附加的行為(被代理對象沒有的行為)
                    System.out.println("Size = " + list.size());
                    System.out.println(Arrays.toString(list.toArray()));
                }
            }
            // 將之前執(zhí)行被代理對象的方法得到的返回值返回
            return retValue;
        }   
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市盅藻,隨后出現(xiàn)的幾起案子购桑,更是在濱河造成了極大的恐慌畅铭,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件勃蜘,死亡現(xiàn)場離奇詭異硕噩,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)缭贡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進(jìn)店門炉擅,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人阳惹,你說我怎么就攤上這事谍失。” “怎么了穆端?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵袱贮,是天一觀的道長。 經(jīng)常有香客問我体啰,道長攒巍,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任荒勇,我火速辦了婚禮柒莉,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘沽翔。我一直安慰自己兢孝,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布仅偎。 她就那樣靜靜地躺著跨蟹,像睡著了一般。 火紅的嫁衣襯著肌膚如雪橘沥。 梳的紋絲不亂的頭發(fā)上窗轩,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天,我揣著相機(jī)與錄音座咆,去河邊找鬼痢艺。 笑死,一個胖子當(dāng)著我的面吹牛介陶,可吹牛的內(nèi)容都是我干的堤舒。 我是一名探鬼主播,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼哺呜,長吁一口氣:“原來是場噩夢啊……” “哼舌缤!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤友驮,失蹤者是張志新(化名)和其女友劉穎漂羊,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體卸留,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡走越,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了耻瑟。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片旨指。...
    茶點(diǎn)故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖喳整,靈堂內(nèi)的尸體忽然破棺而出谆构,到底是詐尸還是另有隱情,我是刑警寧澤框都,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布搬素,位于F島的核電站,受9級特大地震影響魏保,放射性物質(zhì)發(fā)生泄漏熬尺。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一谓罗、第九天 我趴在偏房一處隱蔽的房頂上張望粱哼。 院中可真熱鬧,春花似錦檩咱、人聲如沸揭措。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽绊含。三九已至,卻和暖如春炊汹,著一層夾襖步出監(jiān)牢的瞬間艺挪,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工兵扬, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人口蝠。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓器钟,卻偏偏與公主長得像,于是被迫代替她去往敵國和親妙蔗。 傳聞我的和親對象是個殘疾皇子傲霸,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 國家電網(wǎng)公司企業(yè)標(biāo)準(zhǔn)(Q/GDW)- 面向?qū)ο蟮挠秒娦畔?shù)據(jù)交換協(xié)議 - 報(bào)批稿:20170802 前言: 排版 ...
    庭說閱讀 10,970評論 6 13
  • 轉(zhuǎn)至元數(shù)據(jù)結(jié)尾創(chuàng)建: 董瀟偉,最新修改于: 十二月 23, 2016 轉(zhuǎn)至元數(shù)據(jù)起始第一章:isa和Class一....
    40c0490e5268閱讀 1,715評論 0 9
  • 從三月份找實(shí)習(xí)到現(xiàn)在,面了一些公司昙啄,掛了不少穆役,但最終還是拿到小米、百度梳凛、阿里耿币、京東、新浪韧拒、CVTE淹接、樂視家的研發(fā)崗...
    時芥藍(lán)閱讀 42,247評論 11 349
  • 一、概述 1叛溢、概念: 1塑悼、生活中的代理:就是常說的代理商,從廠商將商品賣給消費(fèi)者楷掉,消費(fèi)者不用很麻煩的到廠商在購買了...
    玉圣閱讀 269評論 0 0
  • 原文: Dyanmic Proxy Classes 介紹 一個動態(tài)代理類是實(shí)現(xiàn)了多個接口存在于運(yùn)行時的類厢蒜,這樣,一...
    半黑月缺閱讀 943評論 0 0