|
|
|
class Database { |
|
public User getUser(int userId) { |
|
|
|
return new User(userId); |
|
} |
|
} |
|
|
|
class UserService { |
|
private Database db; |
|
|
|
public UserService() { |
|
this.db = new Database(); |
|
} |
|
|
|
public User getUserInfo(int userId) { |
|
return db.getUser(userId); |
|
} |
|
} |
|
|
|
|
|
class LooselyCoupledUserService { |
|
private Database db; |
|
|
|
public LooselyCoupledUserService(Database database) { |
|
this.db = database; |
|
} |
|
|
|
public User getUserInfo(int userId) { |
|
return db.getUser(userId); |
|
} |
|
} |
|
|
|
|
|
interface DatabaseInterface { |
|
User getUser(int userId); |
|
} |
|
|
|
class DatabaseImpl implements DatabaseInterface { |
|
public User getUser(int userId) { |
|
|
|
return new User(userId); |
|
} |
|
} |
|
|
|
class DecoupledUserService { |
|
private DatabaseInterface db; |
|
|
|
public DecoupledUserService(DatabaseInterface database) { |
|
this.db = database; |
|
} |
|
|
|
public User getUserInfo(int userId) { |
|
return db.getUser(userId); |
|
} |
|
} |
|
|
|
|
|
class User { |
|
private int id; |
|
|
|
public User(int id) { |
|
this.id = id; |
|
} |
|
} |
|
|
|
public class CouplingExamples { |
|
public static void main(String[] args) { |
|
|
|
UserService tightlyCoupleddService = new UserService(); |
|
User user1 = tightlyCoupleddService.getUserInfo(1); |
|
|
|
|
|
Database database = new Database(); |
|
LooselyCoupledUserService looselyCoupleddService = new LooselyCoupledUserService(database); |
|
User user2 = looselyCoupleddService.getUserInfo(2); |
|
|
|
|
|
DatabaseInterface databaseInterface = new DatabaseImpl(); |
|
DecoupledUserService decoupledService = new DecoupledUserService(databaseInterface); |
|
User user3 = decoupledService.getUserInfo(3); |
|
|
|
System.out.println("Coupling examples created successfully."); |
|
} |
|
} |
|
|