Translation Tipatterns - Object Quantity

zhaozj2021-02-16  111

Object quantity

The two modes described here can be used separately to control the number of objects.

Singleton can actually be considered a special case of object pool, but the application and single piece of object pool (Singleton) is so different, it is necessary to distinguish between the two. of.

Singleton

Singleton provides a way to exist a particular type and can only be an object. It may be the simplest mode. One important aspect of a single piece (Singleton) is to provide a global access point. Singleton is an alternative to the global variable in C.

In addition, single-piece often provides registration (Lookup) features - You can find other objects from single items (Find References to Other Objects).

Singleton can be found in Java reservoirs, but the following provides a more direct example.

//: Singleton: SingletonPattern.java

// The Singleton Design Pattern: you can

// NEVER Instantiate More Than One.

Package Singleton;

Import junit.framework. *;

// Since this isn't inherited from acloneable

// base class and cloneability isn't added,

// MAKING IT Final Prevents Cloneability from

// being added through inheritance:

Final Class Singleton {

Private staton Singleton S = New Singleton (47);

Private INT i;

Private Singleton (INT X) {i = x;}

Public static singleleton getReference () {

Return S;

}

Public int getValue () {RETURN I;

Public void setValue (int x) {i = x;}

}

Public Class SingletonPattern Extends Testcase {

Public void test () {

Singleton S = Singleton.getReference ();

String result = "" s.getValue ();

System.out.println (Result);

Assertequals (Result, "47");

Singleton S2 = Singleton.getReference ();

S2.SetValue (9);

Result = "" s.getValue ();

System.out.println (Result);

Assertequals (Result, "9");

Try {

// can't do this: Compile-Time Error.

// Singleton S3 = (Singleton) s2.clone ();} catch (exception e) {

Throw new runtimeException (e);

}

}

Public static void main (String [] args) {

JUnit.textui.teStrunner.run (SingletonPattern.class);

}

} ///: ~

The key to single-piece mode is to prevent users from creating objects in any other way, but only the way you are provided. All constructor must be declared as private (private) and must have at least a constructor, otherwise the compiler will help you create a default constructor with package privileges.

At this point (At this point), you decide how to create an object. In the above example, the object is created, but you can also wait until the client will request a request to create an object. Whether it is, (created) object must be stored in a private method (PUBLIC METHODS). In the above example, getReference () returns a reference to the single object. The remaining interface (GetValue () and setValue ()) are regular class interfaces.

In addition, Java allows you to create objects using cloning. In this example, this class declares that Final is to prevent objects from creating through the cloning method. Because Singleton is inherited directly from Object, because Clone () is a protected method, it cannot be used (copy object), and if it makes it makes a compile time error.

However, if a class that overloads the clone () method is inherited in the way, and the cloneable interface is implemented. In order to prevent the object from being cloned, the Clone () method must be overruited and a CloneNotSupportedException exception is required. This is also said in Appendix A of Thinking in Java Second Edition. (You can also reload the clone () method makes it only returns this, but this has certain deceptive, the client programmer will certainly think he is cloning (copy) that object, but in fact he handles or It turns out that object.) In fact, this is not exactly, even what is said above, you can still use the reflection to call the clone () method (really like this? Because the clone () method is affected Protected, so I am not so definite. If this is this, it must throw the ClonyNotSupportedException exception, which is the only way to ensure that the object is not cloned.)

Exercise

1. SingletonPattern.java always creates an object, even if this object will never be used. Use the method of latenn initialization to modify this program so that the single object is only created when it is used for the first time.

2. Create A Registry / Lookup Service That Accept A Java Interface and Produces A Reference To An Object That Implements That Interface. Object Pool

There is no restriction that only one object can be created. This technique is equally applicable to creating a fixed number of objects, but in this case you have to face the problem of how to share objects in the object pool. If the shared object is very problematic, you can consider the check-out-out shared object as a solution. For example, in terms of a database, a business database usually limits the number of connections that can be used at a certain time. The following example implements the management of these database connections with the Object Pool. First, the basic management of the A pool of objects is implemented as a separate class.

//: Singleton: poolmanager.java

Package Singleton;

Import java.util. *;

Public class poolmanager {

Private static class poolitem {

Boolean Inuse = FALSE;

Object Item;

POOLITEM (Object item) {this.Item = item;}

}

Private arraylist items = new arraylist ();

Public Void Add (Object Item) {

Items.Add (New poolitem (item));

}

Static Class EmptyPoolXception Extends Exception {}

Public Object Get () throws emptypoolexception {

For (INT i = 0; I

PoolItem Pitem = (poolitem) items.get (i);

IF (pitem.inuse == false) {

Pitem.INUSE = True;

Return Pitem.Item;

}

}

// Fail Early:

Throw new emptypoolexception ();

// return null; // delayed failure

}

Public void release (Object item) {

For (INT i = 0; I

PoolItem Pitem = (poolitem) items.get (i);

IF (item == pitem.item) {

Pitem.INUSE = FALSE;

Return;

}

}

Throw New RuntimeException (Item "Not Found");

}

} ///: ~

//: Singleton: ConnectionPoolDemo.java

Package Singleton;

Import junit.framework. *;

Interface connect {

Object get ();

Void Set (Object X);

}

Class Connection IMPLEments Connection {

Public Object get () {return null;} public void set (object s) {}

}

Class connectionPool {// a singleton

Private static poolmanager pool = new poolmanager ();

Public Static Void AddConnections (int Number) {

For (int i = 0; i

Pool.Add (New ConnectionImplementation ());

}

Public static connection getConnection ()

Throws poolmanager.emptypoyal {

Return (Connection) pool.get ();

}

Public Static Void ReleaseConnection (Connection C) {

Pool.release (C);

}

}

Public class connectionpoolDemo extends testcase {

STATIC {

ConnectionPool.AddConnections (5);

}

Public void test () {

Connection C = NULL;

Try {

C = connectionPool.getConnection ();

} catch (poolManager.emptypoolexception e) {

Throw new runtimeException (e);

}

C.SET (New Object ());

C.Get ();

ConnectionPool.releaseConnection (C);

}

Public void test2 () {

Connection C = NULL;

Try {

C = connectionPool.getConnection ();

} catch (poolManager.emptypoolexception e) {

Throw new runtimeException (e);

}

C.SET (New Object ());

C.Get ();

ConnectionPool.releaseConnection (C);

}

Public static void main (string args []) {

JUnit.textui.teStrunner.run (ConnectionPoolDemo.class);

}

} ///: ~

EXERCIESES does not turn over

1. Add unit tests to connectionpoolDemo.java to demonstrate the problem That the client

May Release The Connection But Still Continue To Use IT.

table of Contents

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

New Post(0)