I read Bruce Eckel Thinking in Java and thereโs an exercise that I just donโt get:
Pg. 161: Exercise 8: (4) After the Lunch.java sample form, create a class called ConnectionManager that manages a fixed array of Connection objects. The client programmer should not explicitly create connection objects , but can only get them through the static method in ConnectionManager. When the ConnectionManager runs out of objects, it returns a null reference. Check the classes in main ().
I came up with the following solution:
import java.util.*;
public class TestConnections {
public static void main( String[] args ) {
Connection cn = Connection.makeConnection();
for (int i = 0; i != 6; ++i) {
Connection tmp = ConnectionManager.newConnectiton();
if ( tmp == null )
System.out.println("Out of Connection objects");
else {
System.out.println("Got object: " + tmp );
}
}
}
}
And the second file in the same directory means that everything ends in the same package by default:
class Connection {
private Connection() {}
static Connection makeConnection() {
return new Connection();
}
}
public class ConnectionManager {
static private Connection[] _connections = new Connection[5];
private ConnectionManager() {}
static public Connection newConnectiton() {
for ( int i = 0; i != _connections.length; ++i ) {
if ( _connections[i] == null ) {
_connections[i] = Connection.makeConnection();
return _connections[i];
}
}
return null;
}
}
, Connection Connection.makeConnection factory, , -, . ConnectionManager.java , , , Connection.
, - , , .
Lunch.java, :
class Soup1 {
private Soup1() {}
public static Soup1 makeSoup() {
return new Soup1();
}
}
class Soup2 {
private Soup2() {}
private static Soup2 ps1 = new Soup2();
public static Soup2 access() {
return ps1;
}
public void f() {}
}
public class Lunch {
void testPrivate() {
}
void testStatic() {
Soup1 soup = Soup1.makeSoup();
}
void testSingleton() {
Soup2.access().f();
}
}