我对java中的松散耦合和紧耦合有一些困惑.我知道松散耦合意味着关于彼此的最少信息和紧耦合意味着依赖.我们知道松散耦合可以通过接口实现和继承实现紧密耦合.
例如:
1)A(界面)<--------------------- B(班级)
2)C(班级)<--------------------- D(班级)
假设这四个类是我整个应用程序的一部分,那么B或D中的更改不会对应用程序产生任何影响(从运行的角度来看).从A或C中删除任何方法或变量都需要在应用程序中进行如此多的更改.所有得分都是2-2,但在C或A中添加新方法是不同的.如果我在C中添加新方法不会影响应用程序但是在A中添加,至少我必须在B和所有实现接口A的类中重写此方法.所以至少在这种情况下它是如何松散耦合的.我的疑问是,继承给予总是紧密耦合.我学习继承是OOP的强大工具之一.如果一个类遵循"是一种关系"则设计然后使用继承.松耦合意味着彼此之间的信息较少.A和C都不知道将来要实现或扩展哪个类,但是在添加B和D之后,现在B不依赖于A,因为它的所有方法都是抽象的,但D也可以覆盖继承特性.
我试图重现Sheridan 对这个问题的回答中建议的内容,以便在将 WPF 与 MVVM 模式一起使用时浏览我的视图。不幸的是,当我这样做时,我遇到了绑定错误。这是确切的错误:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='JollyFinance.ViewModels.MainViewModel', AncestorLevel='1''. BindingExpression:Path=DataContext.DisplayTest; DataItem=null; target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')
Run Code Online (Sandbox Code Playgroud)
当我查看 LoginView.xaml 中的 xaml 代码时,我注意到 Visual Studio 告诉我它无法DataContext.DisplayText在 type 上下文中找到MainViewModel。我尝试过删除DataContext.并保留DisplayText,但无济于事。
除非谢里登的答案有错误,否则我肯定在这里遗漏了一些东西。我应该做什么才能让它发挥作用?
主窗口.xaml:
<Window x:Class="JollyFinance.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:JollyFinance.ViewModels"
xmlns:views="clr-namespace:JollyFinance.Views"
Title="JollyFinance!" Height="720" Width="1280">
<Window.Resources>
<!-- Different pages -->
<DataTemplate DataType="{x:Type vm:LoginViewModel}">
<views:LoginView/>
</DataTemplate>
<DataTemplate DataType="{x:Type vm:TestViewModel}">
<views:Test/>
</DataTemplate> …Run Code Online (Sandbox Code Playgroud) 当我可以简单地使用时,为什么我应该使用Communicating with Other Fragments模式
((MyActivity)getActivity()).doFoo();
在我的Fragment?
我知道松散耦合和紧密耦合的信息.但我暂停什么时候可以决定在哪里和什么时候使用?我不明白什么时候我需要松散耦合和紧密耦合?
请看:http://www.dofactory.com/Patterns/PatternAdapter.aspx#_self1
如果你看适配器类:
///
/// The 'Adapter' class
///
class Adapter : Target
{
private Adaptee _adaptee = new Adaptee();
public override void Request()
{
// Possibly do some other work
// and then call SpecificRequest
_adaptee.SpecificRequest();
}
}
Run Code Online (Sandbox Code Playgroud)
以上用法就像紧紧耦合!我认为紧密耦合是糟糕的用法.但适配器模式紧密耦合使用.当我需要紧密和松散耦合?
从 @RestController 返回 @Entity 而不是 DTO 时是否有任何陷阱?像这样:
@RestController
public class EmployeeRestController {
@Autowired
private EmployeeRepository repository;
@GetMapping("/rest/employee/get/{id}")
public Employee getEmployeeByID(@PathVariable("id") int id) {
return repository.retrieve(id);
}
@Entity
public class Employee {
...
Run Code Online (Sandbox Code Playgroud) c# ×2
java ×2
oop ×2
android ×1
data-binding ×1
fragment ×1
mvvm ×1
navigation ×1
spring ×1
spring-boot ×1
spring-mvc ×1
wpf ×1