Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Bridge pattern
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Java === The following [[Java (programming language)|Java]] program defines a bank account that separates the account operations from the logging of these operations. <syntaxhighlight lang="java"> // Logger has two implementations: info and warning @FunctionalInterface interface Logger { void log(String message); static Logger info() { return message -> System.out.println("info: " + message); } static Logger warning() { return message -> System.out.println("warning: " + message); } } abstract class AbstractAccount { private Logger logger = Logger.info(); public void setLogger(Logger logger) { this.logger = logger; } // the logging part is delegated to the Logger implementation protected void operate(String message, boolean result) { logger.log(message + " result " + result); } } class SimpleAccount extends AbstractAccount { private int balance; public SimpleAccount(int balance) { this.balance = balance; } public boolean isBalanceLow() { return balance < 50; } public void withdraw(int amount) { boolean shouldPerform = balance >= amount; if (shouldPerform) { balance -= amount; } operate("withdraw " + amount, shouldPerform); } } public class BridgeDemo { public static void main(String[] args) { SimpleAccount account = new SimpleAccount(100); account.withdraw(75); if (account.isBalanceLow()) { // you can also change the Logger implementation at runtime account.setLogger(Logger.warning()); } account.withdraw(10); account.withdraw(100); } } </syntaxhighlight> It will output: <pre> info: withdraw 75 result true warning: withdraw 10 result true warning: withdraw 100 result false </pre>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)