Design pattern prototype - work articles (original)

xiaoxiao2021-03-06  71

Design pattern prototype - work articles

This year, I have to pay a job, but because I am addicted to the CS these days, I haven't written my homework now. How can I do it? Who knows that our teachers are most hateful for students. Hey, I have a good skill, that is, the Clone Dafa (commonly known as the Copy Dafa), is because of the skill, it can make my cruel struggle in an invincible place. So I took Zhang San 's homework with Thunder and Early Bell, started to work.

Said here, I have to talk about what is CLONE?

There is an object A. Some valid values ​​have been included in a certain time A. You may need one and a completely the same new object B, and after any changes to b will not affect the value in A, that is Say, A and B are two independent objects, but the initial value of B is determined by the object.

I have a good reason to return, let's get started.

1. Here, first define a copy homework interface:

Public interface CopyHomeWork Extends Cloneable {

Public String gethomework ();

Public void setomework (String homework);

}

2, then define a homework implementation class:

Public Abstract Class HomeWork IMPLEments CopyHomework {

String homework;

Public void setomework (String homework) {

this.homework = homework;

}

Public String gethomework () {

Return this.homework;

}

// Typical call clone () code

Public Object Clone () {

Object Object = NULL;

Try {

Object = super.clone ();

}

Catch (ClonyNotsupportedException Exception) {

System.err.Println ("*** is not cloneable");

}

Return Object;

}

Public Abstract void dohomework (); // Doing an abstract class

}

3. Define Zhang San's job (ZHANGSANHOMEWORK) class:

Public class zhangsanhomework eXtends homework {

Public void dohomework () {

System.out.println ("Zhang San finished the job!");

}

}

4, write test classes:

Public class testcopyHomework {

Public static void main (string args []) {

Zhangsanhomework zhangsanhomework = new zhangsanhomework ();

Homework myhomework = (homework) zhangsanhomework.clone ();

MyHomework.doHomework ();

MyHomework.sethomework ("I am copying industry, don't disturb!");

System.out.println (MyHomeWork.getHomeWork ());

}

}

5. Description:

A: Definition: Specify the type of the object with a prototype instance and create a new object by copying these prototypes. B: prototype mode allows an object to create another customable object, do not need to know any details of how to create, the working principle is: passing a prototype object to the object to be created, this to start the object to be created Request prototype objects to copy them themselves to implement creation.

C: prototype mode finally evolved into Clone.

转载请注明原文地址:https://www.9cbs.com/read-108381.html

New Post(0)