SoftwareArchitectureConcepts / CouplingExamples.java
ozayezerceli's picture
Upload 3 files
cad5b7a verified
raw
history blame
2.04 kB
// Tight Coupling Example
class Database {
public User getUser(int userId) {
// database logic here
return new User(userId);
}
}
class UserService {
private Database db;
public UserService() {
this.db = new Database();
}
public User getUserInfo(int userId) {
return db.getUser(userId);
}
}
// Loose Coupling Example
class LooselyCoupledUserService {
private Database db;
public LooselyCoupledUserService(Database database) {
this.db = database;
}
public User getUserInfo(int userId) {
return db.getUser(userId);
}
}
// Decoupling with Interfaces Example
interface DatabaseInterface {
User getUser(int userId);
}
class DatabaseImpl implements DatabaseInterface {
public User getUser(int userId) {
// database logic here
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);
}
}
// Helper class for the examples
class User {
private int id;
public User(int id) {
this.id = id;
}
}
public class CouplingExamples {
public static void main(String[] args) {
// Tight Coupling
UserService tightlyCoupleddService = new UserService();
User user1 = tightlyCoupleddService.getUserInfo(1);
// Loose Coupling
Database database = new Database();
LooselyCoupledUserService looselyCoupleddService = new LooselyCoupledUserService(database);
User user2 = looselyCoupleddService.getUserInfo(2);
// Decoupling with Interfaces
DatabaseInterface databaseInterface = new DatabaseImpl();
DecoupledUserService decoupledService = new DecoupledUserService(databaseInterface);
User user3 = decoupledService.getUserInfo(3);
System.out.println("Coupling examples created successfully.");
}
}